0

I have been observing this strange behaviour for a while. Now I would like to know the reason.

See the example below.

Can someone explain why - and whether there are other options more similar to the first version that do what the second does.

>>> a
>>> [1, 0, 1, 1]

>>> for el in a:
        el = 1

>>> a
>>> [1, 0, 1, 1]

>>> for i in range(len(a)):
        a[i] = 1

>>> a
>>> [1, 1, 1, 1]

4 Answers 4

3

Your first snippet:

for el in a:

Gets only the values of the items in a, they're not references to the items in the list. So when you try to reassign it, you only change the value of el, not the item in your list.

While this:

a[i]

Retrieves the items of a themselves, not just the values.

To change all the values of a, you can create a new copy and reassign it back to a:

a = [1 for _ in a]

This is the most effective way. If you want to have both the value, and the index to reassign it, use enumerate:

for index, el in enumerate(a):
    print el #print the current value
    a[index] = 1 #change it,
    print el #and print the new one!

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Well that was a quick response! Thanks, did not know that.
Well, el is a reference to the item itself. But no it's not a reference to the position in the list, which I guess is what you meant.
1

I generally end up using something like this:

a = [1 for el in a]

List comprehension is my preferred way of updating items in a list avoiding indices.

Comments

0

Pythons variables are names for objects, not names for positions in memory. Hence

el = 1

Does not change the object el is pointing to to be 1. Instead it make el now point to the object 1. It does not modify anything in the list at all. For that you have to modify the list directly:

a[2] = 1

Comments

0

fast enumeration gives a immutable copy of the element thus the speed advantage over the index iteration method.

for el in a:# el is immutable

where as

for i in range(len(a)):
        a[i] = 1

modifies the value at its memory location as listname[<index>] is actually baseaddress+index*offset. one of the reasons why index start with zero

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.