Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python list comprehension is it possible to access the item index?

People also ask

Can we access list using index in Python?

You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .

Can list be accessed by index?

Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like: var temp = list1["DesiredMember"];

How do you access the list of items in Python?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.


list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]

If you use enumerate, you do have access to the index:

list2 = [x for ind, x in enumerate(list1) if 4>ind>0]

Unless your real use case is more complicated, you should just use a list slice as suggested by @wim

>>> list1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> [x for ind, x in enumerate(list1) if 4 > ind > 0]
['one', 'two', 'three']
>>> list1[1:4]
['one', 'two', 'three']

For more complicated cases - if you don't actually need the index - it's clearer to iterate over a slice or an islice

list2 = [x*2 for x in list1[1:4]]

or

from itertools import islice
list2 = [x*2 for x in islice(list1, 1, 4)]

For small slices, the simple list1[1:4]. If the slices can get quite large it may be better to use an islice to avoid copying the memory


For those wondering, you can just as easily store the matching indices as the result of the list comprehension if your use-case requires it. It may be that you need to evaluate the value of each item in the list to determine if it matches some value or pattern, and that you just want to obtain a list of the matching indices for later processing rather than the matching values.

This can be done as shown below:

>>> values = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> search = ['one', 'three', 'five']
>>> matches = [i for i, x in enumerate(values) if x in search]
>>> print(matches)
[1, 3, 5]

The important part above is the use of the [i for i, x in enumerate(l) if ...] pattern in the list comprehension, where the index i is being captured rather than the value x which would be achieved using the more typical [x for x in l if ...] or the alternate [x for i, x in enumerate(l) if ...] enumeration list comprehension patterns.