Search code examples
pythonfor-loopreturnlist-comprehension

Python - print and return in for loops


I've just started learning Python. I saw an interesting code from here that the author used to explain short-circuiting. The code is as follows:

>>> def fun(i):
...     print "executed"
...     return i
... 

I tried to call fun(1). The output is the following and it makes perfect sense to me.

>>> fun(1)
executed
1

Then I tried [fun(i) for i in [0, 1, 2, 3]], and the output looked like this:

>>> [fun(i) for i in [0, 1, 2, 3]]
executed
executed
executed
executed
[0, 1, 2, 3]

I was expecting something like this:

executed
0
executed
1
executed
2
executed
3

Can anyone tell me what I got wrong? Thank you!


Solution

  • Try doing

    l = [fun(i) for i in [0, 1, 2, 3]]
    

    This will output

    executed
    executed
    executed
    executed

    Then just execute l, this will display the value of l, that is to say: [0, 1, 2, 3]

    So when you are executing

    >>> [fun(i) for i in [0, 1, 2, 3]]
    

    This calls fun(0), fun(1), and so on, and displays executed, then it displays the computed value: [0, 1, 2, 3]