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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: