+ 1

print(*(animals.get(i) for i in x))

hei guys. could you briefly explain me the function of the asterix in the print line of the below code please? Removing it results in the following output: "<generator object <genexpr> at 0x7f81bc9603c0>" ### animals = {"Meow": "Lion", "Woof": "Dog", "Kwak": "Duck", "Tweet": "Bird"} x = input().split() print(*(animals.get(i) for i in x)) ###

7th Nov 2022, 12:05 PM
Eren Kılıçlar
Eren Kılıçlar - avatar
2 Respostas
+ 4
(animals.get(i) for i in x) is a generator expression. Think of it as something between a list comprehension and lambda iterator. It yields results. for example, if you input Meow Tweet Woof it will output Lion Bird Dog the results are not evaluated immediately. you can use next to yield them one by one, or you can use * to unpack them in one step. similarly,you can unpack the keys using print(*(animals.get(i) for i in animals.keys())) which works like for i in animals.keys(): print(animals.get(i)) https://dbader.org/blog/JUMP_LINK__&&__python__&&__JUMP_LINK-generator-expressions#:~:text=Generator%20expressions%20are%20similar%20to,t%20be%20restarted%20or%20reused.
7th Nov 2022, 12:56 PM
Bob_Li
Bob_Li - avatar
+ 2
Decent breakdown there. Thank you!
7th Nov 2022, 2:34 PM
Eren Kılıçlar
Eren Kılıçlar - avatar