First page Back Continue Last page Overview Graphics

Contained in List / Get the Index

It's possible to test with el in list, if „el“ is contained in the list list.

The result is True, if „el“ is contained once or multiple times in the list.

If you are interested in the exact number, you can use the method count().

>>> colors=['blue', 'green', 'red', 'green']

>>> 'green' in colors

True

>>> colors.count('green')

2

>>> colors.count('black')

0

The position of an element x inside of a list:

lst.index(x[, i[, j]])

The optional parameter i sets a start index and j an end position for the search.

>>> colors=['blue', 'green', 'red', 'green']

>>> colors.index('green')

1

>>> colors.index('green',2)

3

>>> colors.index('green',2,4)

3

Finding the Indices of all Matching Items

l = ["a", "b","a","b","a","x"]

i = - 1

while "a" in l[i+1:]:

i = l.index("a",i+1)

print(i)