Accessing the index in Python 39for39 loops

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

How do I access the index itself for a list like the following?

ints = [8, 23, 45, 12, 78]

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

Answers

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

https://docs.python.org/3/library/functions.html#enumerate https://docs.python.org/3/library/functions.html#enumerate

for idx, val in enumerate(ints):
    print(idx, val)

https://www.python.org/dev/peps/pep-0279/ https://www.python.org/dev/peps/pep-0279/

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils