-4

Suppose you have a dictionary and a function that performs some arbitrary task on said dictionary, such as below:

dictionary = {
    "a": 1,
    "b": 2,
    "c": 3,
}

def get_values(d: dict) -> list:
    return [d[key] for key in d]

For each iteration of this for loop, is the function "get_values(dictionary)" called on each iteration, or just at the beginning?

for i in get_values(dictionary): 
    pass

Please give a brief explanation

John Gordon
  • 29,573
  • 7
  • 33
  • 58
Darragh
  • 1
  • 1
  • @JohnGordon, not a homework question, I'm just curious to learn, rather than condescendingly post ignorant comments on other members' posts. – Darragh Jul 29 '23 at 21:36
  • 5
    If you add a `print` statement inside `get_values`, how often do you see its output? – mkrieger1 Jul 29 '23 at 21:39
  • This is [the same as with `range` in Python 2](https://stackoverflow.com/a/15902931/15032126). – Ignatius Reilly Jul 29 '23 at 22:54
  • As an aside to the actual question... *return list(d.values())* would suffice – DarkKnight Jul 30 '23 at 06:45
  • if you return a list, then it is called once, if you return a generator (i.e. using yield) then it can get called more than once. There's lots of ways to turn functions into generators, like `(a for a in mydict.values())` or`iter(mydict.values()) ` . See https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators to understand iterators and generators more – toppk Jul 30 '23 at 06:55

1 Answers1

0

In the for loop for i in get_values(dictionary):, the function get_values(dictionary) is called once before the loop starts. It retrieves the values from the dictionary and returns a list [1, 2, 3]. The loop then iterates over this list, and at each iteration, the value from the list is assigned to the variable i.