0

I want to make changes to a list in-place such that if the list is l1 = [0, 1, A, B], then I can replace the alphabetical values with numbers.

I tried using the following code for it:

for x in l1:
    if x == 'A':
        x = 10

However, when I look at the list again, it is still the same and A has not been changed to 10. Why is this code not working?

I tried using the indices instead as well, but that did not work either.

for i in range(len(l1)):
     if l1[i] == 'A':
        l1[i] = 10
  • 1
    Possible duplicate of [Can't modify list elements in a loop Python](https://stackoverflow.com/questions/19290762/cant-modify-list-elements-in-a-loop-python) – Carcigenicate Oct 27 '19 at 02:32

1 Answers1

1

In Python things are always passed by value. The 'x' variable in the for loop is a copy of the elements in the list not the pointer/reference of the list elements.

You can change the value of the list by directly indexing it.

One way to achieve that is as follows..

for i,x in enumerate(l1): If x == 'A': l1[i] = 10

Assuming A variable points to value 'A' !

Vivek
  • 21
  • 3