-2
list = [1,2,3] # I want to change it to [2,3,4]
for number in list:
    number += 1
print(list) # The result is still [1,2,3]
list = [1,2,3]
i = 1
while i<=len(list):
    list[i-1] += 1
    i += 1
print(list) # Now the result is [2,3,4]

I want to know the reason why the first for loop won't change the value

vannear
  • 1
  • 1
  • you should not use `list` for the name of the list and `i` should start from `0` – Meowcolm Law Sep 02 '20 at 09:17
  • `number` is a separate variable that holds just the value of an element from your list. It has no underlying link to the list element it was copied from. – khelwood Sep 02 '20 at 09:19

1 Answers1

0

I want to know the reason why the first for loop won't change the value

Because you're not assigning anything back to the list, and numbers are immutable.

It would be a different story if you were modifying a mutable object, e.g. a list:

>>>
>>> l = [[], []]
>>> for x in l:
...   x += [1]  # append an element into the list object(s)
...
>>> l
[[1], [1]]
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172