[ad_1]
enumerate()
is a built-in function in Python that allows you to have an automatic counter while looping over iterables.
Python enumerate()
Function #
The enumerate()
function takes the following form:
enumerate(iterable, start=0)
The function accepts two arguments:
iterable
– An object that supports iteration.start
– The number from which the counter starts. This argument is optional. By default, counter starts from 0.
enumerate()
returns an enumerate object on which you can call the __next__()
(or next()
in Python 2) method to get a tuple
containing a count and the current value of the iterable.
Here is an example of how to create a list of tuples using list()
and how to loop over an iterable:
directions = ["north", "east", "south", "west"]
list(enumerate(directions))
for index, value in enumerate(directions):
print("{}: {}".format(index, value))
[(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]
0: north
1: east
2: south
3: west
If the zero-based indexing doesn’t work for you, choose another starting index for the enumeration:
directions = ["north", "east", "south", "west"]
list(enumerate(directions, 1))
[(1, 'north'), (2, 'east'), (3, 'south'), (4, 'west')]
The enumerate()
function works on any iterable object. An iterable is a container that can be iterated over. Putting it in simple words, it means an object that you can loop over with a for
loop. Most of the built-in objects in Python like strings, lists, and tuples are iterables.
Write More Pythonic Code with enumerate()
#
Python’s for
loop is totally different from the traditional C-style for
loop which is available in many programming languages. The for
loop in Python is equivalent to other languages’ foreach
loop.
A common technique used by new Python developers to get the corresponding index when dealing with iterables is to use either the range(len(...))
pattern or set and increment a counter:
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for i in range(len(planets)):
print("Planet {}: {}".format(i, planets[i]))
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
i = 0
for planet in planets:
print("Planet {}: {}".format(i, planet))
i += 1
The loops above can be rewritten in more idiomatic way using enumerate()
:
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for index, value in enumerate(planets):
print("Planet {}: {}".format(index, value))
All methods will produce the same output:
Planet 0: Mercury
Planet 1: Venus
Planet 2: Earth
Planet 3: Mars
Planet 4: Jupiter
Planet 5: Saturn
Planet 6: Uranus
Planet 7: Neptune
Conclusion #
In this article, we have shown you how to use the Python’s enumerate()
function.
If you have any questions or feedback, feel free to leave a comment.
[ad_2]
Source link