Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating in Python lists - does it copy or use iterator?

I have a list like this

a = [ [ 1,2,3 ], [ 4,5,6] ]

If I write

for x in a:
    do something with x

Is the first list from a copied into x? Or does python do that with an iterator without doing any extra copying?

like image 576
smilitude Avatar asked Apr 07 '12 13:04

smilitude


People also ask

How does Python iterate over a list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by refering to their indexes.

Is list iterable or iterator in Python?

For example, a list is iterable but a list is not an iterator. An iterator can be created from an iterable by using the function iter(). To make this possible, the class of an object needs either a method __iter__, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.

Does enumerate make a copy?

No, it doesn't. It lazily iterates the iterable you pass in while the loop executes.


1 Answers

Python does not copy an item from a into x. It simply refers to the first element of a as x. That means: when you modify x, you also modify the element of a.

Here's an example:

>>> a = [ [ 1,2,3 ], [ 4,5,6] ]
>>> for x in a:
...     x.append(5)
... 
>>> a
[[1, 2, 3, 5], [4, 5, 6, 5]]
like image 88
Simeon Visser Avatar answered Sep 28 '22 06:09

Simeon Visser