← Go Back
The result is an iterable object containing tuples, within which the first value is a number corresponding to the position of the language in the
By default the positions start from zero, but the start number can be given as the second argument.
The
This method is faster, more readable and pythonic than the following:
enumerate() Built-in Function
enumerate()
takes an iterable object it
and returns another iterable object whose elements are tuples of two objects, the first of which indicates the position of an element belonging to it
, and the second is the element itself. For example:>>> languages = ["Java", "C", "C++", "Rust", "Elixir"]
>>> list(enumerate(languages))
[(0, 'Java'), (1, 'C'), (2, 'C++'), (3, 'Rust'), (4, 'Elixir')]
The result is an iterable object containing tuples, within which the first value is a number corresponding to the position of the language in the
languages
list, and the second is the name of the language itself.By default the positions start from zero, but the start number can be given as the second argument.
>>> list(enumerate(languages, 1))
[(1, 'Java'), (2, 'C'), (3, 'C++'), (4, 'Rust'), (5, 'Elixir')]
The
enumerate()
function is especially useful when using a for loop requires both the elements of an iterable and their indexes:>>> for i, language in enumerate(languages):
... print(i, language)
...
0 Java
1 C
2 C++
3 Rust
4 Elixir
This method is faster, more readable and pythonic than the following:
>>> for i in range(len(languages)):
... print(i, languages[i])
...
0 Java
1 C
2 C++
3 Rust
4 Elixir
🐍 You might also find interesting: