Python language basics 48: getting a counter in for-each loops

Introduction

In the previous post we looked at two ways to reverse the elements in a list. The reverse function operates directly on the list whereas the reversed function returns an independent list with the elements of the source reversed.

In this post we’ll look at a case where you may need a counter while looping through a list.

Looping with counters

We looked at while and for-each loops in this course before.

We’ll revisit for-each loops a bit. Occasionally you may need an item counter. E.g. you might want to print the index number of the current element:

#1: USA
#2: UK
#3: Uganda
#4: Kenya

…etc., for each item in the list of countries.

Consider the following list of cities:

cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]

One way to introduce a counter is to manually create one an increase its value for each iteration:

counter = 1
for city in cities:
    print("City #{0}: {1}".format(counter, city))
    counter += 1

City #1: Stockholm
City #2: Budapest
City #3: Berlin
City #4: Paris
City #5: Birmingham
City #6: Zürich

However, there’s a more elegant way. The ‘enumerate’ function accepts a collection and for each iteration returns a [tuple] with 2 elements: the 0-based index and the actual object from the collection. Let’s see it in action:

for city_enum in enumerate(cities):
    print("City #{0}: {1}".format(city_enum[0] + 1, city_enum[1]))

…which prints the same list as above.

We add 1 to the index element so that we don’t start the printed list with #0 which looks awkward.

The elements in a tuple can be assigned to a variable each in the following way:

for index, city in enumerate(cities):
    print("City #{0}: {1}".format(index + 1, city))

The local variable ‘index’ will be assigned the first element of the tuple in each iteration, i.e. the index itself. ‘city’ will be assigned the second element in the tuple, i.e. the city name. The above code results in the same printout as before.

In the next post we’ll start looking into sets in Python.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: