How to Obtain a Subarray in Python 3 [Duplicate]

How to Obtain a Subarray in Python 3 [Duplicate]

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

1

2 Answers

Use list comprehension for this

print ([i[3:6] for i in a[0:2]])
0

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]]
Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.