How to Get a Certain Element in a List, Given the Position

Finding the index of an item in a list

>>> ["foo", "bar", "baz"].index("bar")
1

See the documentation for the built-in .index() method of the list:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Caveats

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.

This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the start and end parameters can be used to narrow the search.

For example:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514

The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.

Only the index of the first match is returned

A call to index searches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed, index cannot solve the problem:

>>> [1, 1].index(1) # the `1` index is not found.
0

Instead, use a list comprehension or generator expression to do the search, with enumerate to get indices:

>>> # A list comprehension gives a list of indices directly:
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> # A generator comprehension gives us an iterable object...
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> # which can be used in a `for` loop, or manually iterated with `next`:
>>> next(g)
0
>>> next(g)
2

The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.

Raises an exception if there is no match

As noted in the documentation above, using .index will raise an exception if the searched-for value is not in the list:

>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

If this is a concern, either explicitly check first using item in my_list, or handle the exception with try/except as appropriate.

The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.

How to select an item from a list by knowing its position in the list

If you know the index of an element on the list you can use listName[index] to get it's value.
For example

lst = [a,b,c,d,e]
print(lst[0]) # returns a

How to get item's position in a list?

Hmmm. There was an answer with a list comprehension here, but it's disappeared.

Here:

 [i for i,x in enumerate(testlist) if x == 1]

Example:

>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]

Update:

Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:

>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7

Now we'll construct a generator...

>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7

and niftily enough, we can assign that to a variable, and use it from there...

>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7

And to think I used to write FORTRAN.

How to find the position of an element in a list , in Python?

for index, s in enumerate(stocks_list):
print index, s

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

Check if an element in a list has a value in a defined position

To solve this you can use slice notation, which lets you index from the right, as well as a list comprehension.

Indexing from the right works like this:

input:

my_string = '1001'
my_string[-3:-1]

output:

'00'

This is because [-3:] starts indexing in the third position from the right, and [:-1] indexes up to but not including the last position in the right.

Next, you want to sum all elements that are in your dictionary for which the key meets this condition. You can do this with a list comprehension:

sum([counts[key] for key in counts.keys() if key[-3:-1] == '00'])
0.251953125

Breaking this into steps:

[counts[key] for key in counts.keys()]

This creates a new list that has all the values of your original list. Not useful on its own.

But by adding in the conditional: "if key[-3:-1] == '00'", we filter down the list to only having the values where the third from the right and second from the right, what you're calling position 2 and position 1, are both '0'.

Thus, the new list only has values from the keys you're selecting for, and then we sum those values.

Hope this helps!



Related Topics



Leave a reply



Submit