Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
List basics
Lists with if statements and loops
14. Iterating over elements with indices
Lists in functions
Summary

Instruction

Good. The special for loop is extremely useful, but what if we want to know the index of the current element inside the loop? For instance, we want to print the company name as well as its position in the list. To do so, we can construct our loop in the following way:

# print each company
for i in range(0, len(companies)):
  print(companies[i] + ' is number ' + str(i+1) + ' in Europe.')

This time, we defined a temporary variable named i (that's a frequent name, but again, you can call it anything) in the range from 0 (which is the first index) up to, but not including, the length of the list (which is the maximum valid index plus one).

In this way, we can use companies[i] to access a given element, and we can still print i to get the position in the ranking. Note that because indices start at 0 instead of 1, we used str(i+1) to start numbering from 1.

Exercise

You are now given two lists: tourist_arrivals and months. The second list stores the names of the months. Use both lists together to produce 12 sentences:

Tourist arrivals in January 2016 were 7.8 million people.
Tourist arrivals in February 2016 were 9.0 million people.

And so on.

Stuck? Here's a hint!

Use the following for loop:

for i in range(0, len(tourist_arrivals)):

Inside the single loop, use i to access both tourist_arrivals[i] and months[i].