Understanding the Python Python List for Behavior

EDIT: my stupid logic overtook me. None of them are the result of returning a call. Ok, I run some tests in python, and I came across some difference in the execution of orders, which leads me to understand how it is implemented, but I would like to run it for you great people, to see if I'm right, or there are more . Consider this code:

>>> a = ["a","b","c","d","e"]
>>> def test(self,arg):
...     print "testing %s" %(arg)
...     a.pop()
... 
>>>[test(elem) for elem in a]
testing a
testing b
testing c
[None, None, None]
>>> a
['a', 'b']
#now we try another syntax
>>> a = ["a","b","c","d","e"]
>>> for elem in a:
...     print "elem is %s"%(elem)
...     test(elem)
... 
elem is a
testing a
elem is b
testing b
elem is c
testing c
>>> a
['a', 'b']
>>> 

Now this tells me that for elem in a: gets the next iterative element, then applies the body, while understanding somehow calls the function for each list item before the code actually executes in the function, so changing the list from the function (pop) leads to ] none, none, none]

Is it correct? what's going on here?

thank

+5
3

test return, None s. python , .

:

>>> def noop(x): pass
... 
>>> [noop(i) for i in range(5)]
[None, None, None, None, None]

, for .

+4
>>> a = ["a","b","c","d","e"]
>>> i = iter(a)
>>> next(i)
'a'
>>> a.pop()
'e'
>>> next(i)
'b'
>>> a.pop()
'd'
>>> next(i)
'c'
>>> a.pop()
'c'
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
+1

He got to "c"and then exhausted the items on the list. Since testit returns nothing, you get [None, None, None].

0
source

All Articles