I and zip() function Question

Hello,
I had a question about the for-loop in the “Pandas Visualizations and Grid Charts Mission” on Page 11.

The URL: Learn data science with Python and R projects

plt.figure(figsize=(10,12))

for i, day in zip(range(1,6), days):
plt.subplot(3, 2, i)
plt.plot(traffic_per_day[day]['Hour (Coded)'], traffic_per_day[day]['Slowness in traffic (%)'])
plt.title(day)
plt.ylim([0,25])

plt.show()

What is the “i” in the for loop and why does it need a comma after it. Also, what is zip()? This is the first time (I think) we’re using this.

Hi, @mtl1212 .

for i, day in zip(range(1,6), days):
In this code you iterate over two things the range (which is the number of subplots) and days list not just one as usual, i is the number in range and day is the day name in days.

zip() is a built-in function in python allows us to loop over multiple lists at the same time.
To know more about looping and zip in python see this : https://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/#What_if_we_need_to_loop_over_multiple_things?

https://realpython.com/python-zip-function/

for i, day here you assign multiple variables at the same time in one line of code and that’s why there is a comma and this is called iterable unpacking.
To Know more about unpacking check this : https://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/#Unpacking_in_a_for_loop

Hope this helps.

5 Likes

The zip() function allows us to iterate over multiple lists at the same time. Consider the example below:

In [1]: numbers = [1, 2, 3]

In [2]: letters = ['a', 'b', 'c']

In [3]: for i, j in zip(numbers, letters):
   ...:     print(i)
   ...:     print(j)
   ...:     print('----------')

1
a
----------
2
b
----------
3
c
----------

In that visualization mission, we use i to fill the index number in plt.subplot(3, 2, i), and day to access the dictionary traffic_per_day.

To better understand how zip() works, you can also look at its output:

In [4]: zipped = zip(numbers, letters)

In [5]: list(zipped)
Out[5]: [(1, 'a'), (2, 'b'), (3, 'c')]

5 Likes