Home > Blockchain >  Why can't I manipulate a list items using for in loop? (Python)
Why can't I manipulate a list items using for in loop? (Python)

Time:12-18

Why does this code work as intended (manipulate the list elements):

numbers = [42, 123]
numbers[1] = 5

for index in range(len(numbers)):
      print(numbers[index]) 
      numbers[index] = numbers[index] * 2
      print(numbers[index])
print(numbers)
Output:
84
10
[84, 10]

While this code doesn't:

for number in numbers:
    number = number * 2
    print(number)
print(numbers)
Output:
84
10
[42, 5]

My initial thought is that the for in loop creates a scoped variable number that is equal to the value of numbers[i] and that variable is what gets manipulated and not the list. Is that right?

CodePudding user response:

In the 2nd block of code it is not modifying the elements of the list, it is only modifying the local variable number.

You can use something like enumerate() to loop over the elements and indicies at once:

for i, number in enumerate(numbers):
  numbers[i] = number * 2

CodePudding user response:

Instead of manipulating an existing list, build a new list based on the old one using a list comprehension. Then assign numbers to point to that new list.

numbers = [42, 5]
numbers = [2*n for n in numbers]

A couple of things to note here:

  • This code is much less complicated.
  • For a large list, a comprehension will be significantly faster.
  • Variables in Python are basically references to objects. So when you re-assign numbers, the list [42,5] loses a reference. If it is not referenced elsewhere, it will be garbage-collected.
  • Related