Reputation: 5
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!
Upvotes: 0
Views: 165
Reputation: 36360
>>> def fun(i):
... print "executed"
... return i
...
This is not example of short-circuiting. This is function with side effect - it does write to standard output, which is observable effect besides returning a value.
[fun(i) for i in [0, 1, 2, 3]]
This is list
comprehension. Generally speaking you should have good reason to use function with side effect in such place, PEP 202 explains motivation for list
comprehension as follows:
List comprehensions provide a more concise way to create lists in situations where
map()
andfilter()
and/or nested loops would currently be used.
Someone reading your code therefore will probably assume it has to just create list, without printing elements during this action.
Upvotes: 3
Reputation: 385
Square brakets in this context form a new list, which each element is function fun of according element in [0, 1, 2, 3]. It is called list list-comprehensions. "executed" is printed because during formation of new list function fun is called(for each element in [0, 1, 2, 3]). numbers 0,1,2 and 3 are not printed, because return value of fun is not printed, but put in the new list. To see the new list:
print("new list:",[fun(i) for i in [0, 1, 2, 3]])
Upvotes: 1
Reputation: 2900
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]
Upvotes: 0