Search code examples
pythonfor-loopzip

For loop and zip in python


I have a code that I am trying to understand and I need help.

import numpy as np
Class_numbers=np.array(['a','b','c'])
students_per_class=np.array([10,20,30])
print("Students counts per class:\n{}".format(
{x: y for x, y in zip(Class_numbers, students_per_class)}))

output:

Students counts per class:
{'a': 10, 'b': 20, 'c': 30}

What I understand: 1- we use {} and .format(...) to replace {} with ...

Here are my questions:

Q1- I do not understand "for x, y in zip(Class_numbers, students_per_class)". Is it like a 2d for loop? why we need the zip? Can we have 2d loop with out zip function?

Q2-I am not understanding how x:y works! the compile understand automatically that the definition of x and y (in "x:y") is described in the rest of the line(e.g. for loop)?

P.S: I am expert in MATLAB but I am new to python and it is sometimes very confusing!

Ehsan


Solution

  • Q1: zip is used to merge 2 lists together. It returns the first element of each list, then 2nd element of each list, etc. This is a trick to consider the two lists as key and data to create a dictionary.

    Q2: this is a dictionary (hash), using a method called "dict comprehension". It creates the dictionary shown as the output. If assigned to a variable d, d['a'] = 10, etc.