I want to get a subarray in python 3. I have tried the following.
a = ['abcdefgh', 'abcdefgh' , 'abcdefgh']
print (a[0][3:6])
print (a[1][2:6])
print (a[0:2][3:6])
I get the first two results as expected. But I am not able to obtain the desired result for the 3rd print statement.
Output :
def
cdef
[]
Desired Output :
def
cdef
['def', 'def']
Can anyone tell me how to obtain it
2 Answers
Use list comprehension for this
print ([i[3:6] for i in a[0:2]])
This will work. It will iterate over elements at index 0 and 1 and will slice the array as expected.
[x[3:6] for x in a[0:2]]