Naveera A.
—How can you access the index of each element while using Python’s for
loop?
Let’s say we have the following list:
directions = ['north', 'east', 'south', 'west']
Usually, we don’t need the indexes of the elements. So Python provides a simpler method of looping where instead of retrieving item indexes and looking up each element, we can just loop over the elements directly, like so:
directions = ['north', 'east', 'south', 'west'] for direction in directions: print(direction)
But what if we need the indexes? For example, if we want the following output where each element is printed alongside its index in the list:
0 north 1 east 2 south 3 west
Python’s for
loops are actually foreach loops. A foreach loop makes the code simpler to read but it maintains no counters. So rather than saying “do this n times”, a foreach loop essentially says “do this to everything in the sequence”.
For scenarios where we actually need the index or counter variable, we can use Python’s built-in enumerate
function. The enumerate
function returns an iterable. Each element of this iterable is a tuple containing the index of the item and the original item value, like so:
directions = ['north', 'east', 'south', 'west'] directions_tuples = enumerate(directions) # output [(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]
We can unpack the tuple in two variables and use it in the for
loop, like so:
directions = ['north', 'east', 'south', 'west'] for index, direction in enumerate(directions): print(f"{index} {direction}")
This will print the following output:
0 north 1 east 2 south 3 west
The enumerate
function also takes an optional argument, start
. We can use this argument to change the starting index. By default, the value of start
is 0.
Let’s say we want to print the directions with a natural counting number, we can set the value of start
to 1, like so:
directions = ['north', 'east', 'south', 'west'] for index, direction in enumerate(directions, start=1): print(f"{index} {direction}")
This time we will get the following output:
1 north 2 east 3 south 4 west
There are other ways of accessing index or counter variables, for example using the range
and len
functions, like so:
for index in range(len(directions)): print(f"{index} {directions[index]}")
But using the enumerate
function is the recommended and pythonic way of achieving this result.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.