Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain a subarray in python 3 [duplicate]

Tags:

python

list

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

like image 762
Rohith Avatar asked Jun 27 '16 08:06

Rohith


People also ask

How do I copy a Subarray in Python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

How do you get a subarray from an array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

How do you take Subarray?

Use Arrays. copyOfRange() method to get a subarray.

How do you create a contiguous subarray in Python?

Given an array of numbers, return true if there is a subarray that sums up to a certain number n . A subarray is a contiguous subset of the array. For example the subarray of [1,2,3,4,5] is [1,2,3] or [3,4,5] or [2,3,4] etc. In the above examples, [2, 3] sum up to 5 so we return true .


2 Answers

Use list comprehension for this

print ([i[3:6] for i in a[0:2]])
like image 170
Sardorbek Imomaliev Avatar answered Sep 30 '22 09:09

Sardorbek Imomaliev


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]]
like image 40
Abdul Fatir Avatar answered Sep 30 '22 11:09

Abdul Fatir