Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 421
Ehsan Avatar asked Feb 17 '26 01:02

Ehsan


1 Answers

zip allows you to iterate two lists at the same time, so, for example, the following code

letters = ['a', 'b', 'c']
numbers = [1, 2, 3]

for letter, number in zip(letters, numbers):
    print(f'{letter} -> {number}')

gives you as output

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

when you iterate with zip, you generate two vars, corresponding to the current value of each loop.

like image 144
Freddy Avatar answered Feb 19 '26 14:02

Freddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!