list.pop and print doing funny things
Tim Peters
tim.peters at gmail.com
Tue Sep 21 15:10:55 EDT 2004
[Gordon Williams]
> Why do I get the x printed twice in the sample below? It is like print x is
> being executed twice in each loop.
>
> >>> l = [1,2,3,4]
> >>> for x in l[:]:
> ... print x
> ... l.pop(l.index(x))
> ... print l
> ...
> 1
> 1
> [2, 3, 4]
> 2
> 2
> [3, 4]
> 3
> 3
> [4]
> 4
> 4
> []
> >>>
It's for the same reason 42 is printed once in this example:
>>> 42
42
>>>
That is, at an interactive shell, the result of every expression that
returns a non-None value is displayed. It doesn't make any difference
whether the expressions are buried in loops or if-clauses, etc. Your
"l.pop(l.index(x))" returns a non-None result, so that gets displayed
too.
BTW, note that l.remove(x) is a clearer way to get the effect of
l.pop(l.index(x)), and does not return a non-None result.
More information about the Python-list
mailing list