OshoParth
OshoParth

Reputation: 1552

Getting elements with dynamic range of list in python

I am trying to get the elements of a list in python but with a dynamic range ie if I have two lists ['9','e','s','t','1','2','3'] and ['9','e','1','2','3','s','t'] now I need to access the three numbers including 1, so what I did was reached for 1 and then pass the index value of 1 and extract the desired values ie

s_point = valueList.index('1')
print (valueList[s_point::3]

but it does not seem to work however on const values like

print (valueList[1::3]) 

it seems to work just fine. is there a way I could dynamically pass range of list elements to extract out of list ?

Upvotes: 1

Views: 1732

Answers (3)

kvivek
kvivek

Reputation: 3461

There are three problems

1) s_point = valueList.index('1') print (valueList[s_point::3]

but it does not seem to work,

This is simply because you missed the ending parentheses of the print statement.

2) However, on const values like 1 in this example

print (valueList[1::3]) works

but it will not give the desired output rather prints the first 3 numbers.

3) Assuming when the list valuelist is defined, the alphabets used is in single quotes.

Now for the actual solution part.

If you are looking for the case wherein you need the value 1 or any dynamic value say x and the subsequent three values after that from the list. You can make use of a function or anonymous function called lambda, which should accept a dynamic parameter, and it should return the subsequent 3 or dynamic values. like shown below.

>>>
>>> valuelist = [9, 'e', 's', 't', 1, 2, 3]
>>>
>>> result = lambda x,y: valuelist[valuelist.index(x):valuelist.index(x)+y]
>>> result(1,3)
[1, 2, 3]
>>>
>>>

Upvotes: 0

Alireza HI
Alireza HI

Reputation: 1933

If you want the three items after the s_point index you don't have to use the step which is ::step because the usage is different. Just change your line to this:

valueList[s_point:s_point+3]

output:

>>> [1,2,3]

This way it is going to get the sublist of valueList from the index of s_point to the three which are front of it.

And to know the usage of step as other websites mentioned:

The step is a difference between each number in the result. The default value of the step is 1 if not specified

For example:

valueList[::2]

result:

>>> ['9','s','1','3']

As you see the odd items are not in the list.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82755

Looks like you need

lst = ['9', 'e', '1', '2', '3', 's', 't']
print(lst[lst.index('1'):lst.index('1') + 3])

lst1 = ['9', 'e', 's', 't', '1', '2', '3']
print(lst1[lst1.index('1'):lst1.index('1') +3])

Output:

['1', '2', '3']
['1', '2', '3']

Upvotes: 0

Related Questions