-3

I tried:

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

this works fine:

>>> for q in a:
...     print(q)
... 
0
1
2
3
4

But, if I try to change the (mutable) list objects like so, it doesn't work:

>>> for q in a:
...     q = 0
... 
>>> a
[0, 1, 2, 3, 4]

It seems to me that each time through the loop, q refers to a[n], as n ranges from 0 to 4. So, it would seem, setting q = 0 ought to make the list all value zero.

Any suggestions that are quite Pythonic?

eSurfsnake
  • 647
  • 6
  • 17

1 Answers1

0

Updating iterating variable inside loop does not itself update the iterator you iterate through.

for q in a:
    q = 0

You are just modifying value of q, but do not touch the original list a.

To make all elements in list to 0, use a list-comprehension:

a = [0 for _ in a]
Austin
  • 25,759
  • 4
  • 25
  • 48
  • `a = [0 for _ in a]` does not update the list, it replaces it. It that case you could simply do `a=[0] * len(a)`. – Stephen Rauch Feb 12 '19 at 02:47
  • both good solutions. I think the second suffers if you want to later change a value, however. If you do a=[0]*len(a) then I think if you later do a[2]=10, all of a ( a[n] for n in range len(a) ) will be set to 10, since they all refer to the same object. – eSurfsnake Feb 12 '19 at 04:28