In Python it is somewhat common to go through items from an iterable handle or checking for the existence of a particular item, or whatever the operation. I'm reading the Python documentation again and I come across something that when seen for the first time I did not believe it to be something we say relevant. For example:
>>> animals = ['Cat', 'Dog', 'Elephant']
>>> for animal in animals:
... print(animal, len(animal))
Cat 3
Dog 3
Elephant 8
How can you see itero on a list containing animal names and print the current animal on the loop, as well as the number of characters in the loop. The only operation I do in this example is the printing of their name and the number of characters, I do not try to change the value of them in any way. My question exactly when I think about changing those values.
>>> animals = ['Cat', 'Dog', 'Elephant']
>>> for animal in animals:
... if len(animal) > 3:
animal = animal[:3]
print(animal, len(animal))
Cat 3
Dog 3
Ele 3
>>> print(animals)
The output inside the loop as you can see shows that the variable in the loop was changed, but when printing the list after the loop I see that the list itself was not. This puzzled me because honestly what I am showing here as examples are just things that came to mind that I believe we all thought of doing that is changing a variable during a loop of repetition, another fact is that by studying Python we learn that some of its most basic types such as string
, int
, float
and even tuplas
are immutable, ie because reassignment in the current loop variable did not generate a new string (in the case a string of three characters), thinking in this way I thought to check if the variable
in the current loop was the same as the one in the list being iterated, as follows:
>>> animals = ['Cat', 'Dog', 'Elephant']
>>> for animal in animals:
... print(animal, id(animal))
Cat 140226536948264
Dog 140226536948040
Elephant 140226536875248
>>> animals[0], id(animals[0])
Cat 140226536948264
>>> animals[1], id(animals[1])
Dog 140226536948040
>>> animals[2], id(animals[2])
Elephant 140226536875248
Have you noticed? They are the same identifiers. I do not know in other languages but in the Python documentation it is described that one should create a copy of the iterate before the loop since it does not implicitly do so, but my doubt is still this because I can not change the current item of the loop for
.