Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for n in a list: del n

When I loop over a list, the name that I give within the loop to the elements of the list apparently refers directly to each element in turn, as evidenced by:

>>> a = [1, 2, 3]
>>> for n in a:
...     print n is a[a.index(n)]
True
True
True

So why doesn't this seem to do anything?

>>> for n in a: del n
>>> a
[1, 2, 3]

If I try del a[a.index(n)], I get wonky behavior, but at least it's behavior I can understand - every time I delete an element, I shorten the list, changing the indices of the other elements, so I end up deleting every other element of the list:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for n in a: del a[a.index(n)]
>>> a
[1, 3, 5, 7, 9]

Clearly I'm allowed to delete from the list while iterating. So what's going on when I try to del n inside the loop? Is anything being deleted?

like image 523
Air Avatar asked Nov 20 '25 16:11

Air


1 Answers

Inside the block of any for n in X statement, n refers to the variable named n itself, not to any notion of "the place in the list of the last value you iterated over". Therefore, what your loop is doing is repeatedly binding a variable n to a value fetched from the list and then immediately unbinding that same variable again. The del n statement only affects your local variable bindings, rather than the list.

like image 91
Dolda2000 Avatar answered Nov 23 '25 06:11

Dolda2000