I like the Python syntax a lot, but as I'm coming from C++ I don't get one thing about iterators in Python. In C++ there are 2 kinds of iterators - constant and modifying (non-const). In python it seems (for what I've seen) like there is only the first kind and if you want to modify the elements, you have to use the indexing, which doesn't feel comfortable and so generic to me. Let me illustrate with a simple example:
ab = ["a", "b"]
for (index, lett) in enumerate(ab):
print "Firstly, lett is ab[index]?", lett is ab[index]
lett = str(index)
print lett
print ab[index]
print "But after, lett is ab[index]?", lett is ab[index]
So I wasn't able to modify the list with the iterator.
It just makes Lazy copies (see Wikipedia) as I discovered with the is
operator, so is there a way to say I want it to be a directly modifying iterator instead using the neat
for variable in iterable_object:
syntax?
An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable).
Iterators in Python Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol.
The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops. Object: The object whose iterator has to be created.
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.
The syntax
for x in iterable
does not create any lazy copies -- it assigns the exact objects in the list to x
one after the other. If these objects are mutable, you can modify them:
a = [[1, 2], [3, 4]]
for x in a:
x.append(5)
print a
prints
[[1, 2, 5], [3, 4, 5]]
Your example uses a list of strings. Strings are immutable in Python, so you can't modify them.
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