13

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

1
  • self-proclaimed experts usually claim they know more than they do Commented Apr 11, 2018 at 20:04

5 Answers 5

25

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

Comments

2

zip is useful to enumerate the elements in the 2 different list and make a single list

example :

 x: y for x, y in zip(Class_numbers, students_per_class)

explanation:

  • the element form Class_number is assigned to x which is a "Key" for the dictionary and the students_per_class is assigned to y which is a "value
  • until the loop end it will iterate to dictionary.

Comments

0

just print the line you don't understand to make it clearer...

first we define 2 arrays

Class_numbers=np.array(['a','b','c'])
['a','b','c']

students_per_class=np.array([10,20,30])
[10,20,30]

zip just add them together like

[('a', 10), ('b', 20), ('c', 30)]

now we iterate on each element with x and y and create a dict object (hash map) { key : value}

{'a': 10, 'c': 30, 'b': 20}

Comments

0

there is a trick in using zip:

letters = ('A', 'B', 'C')
numbers = ('1', '2', '3')
let_num = zip(letters, numbers)

use the list() function to display zip:

print(list(let_num))

above code will produce

[('A', '1'), ('B', '2'), ('C', '3')]

please note that, if you want to print again, this will not print anything since we already consumed the zip

print(list(let_num))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.