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?
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.
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.
No, it doesn't. It lazily iterates the iterable you pass in while the loop executes.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With