简体   繁体   中英

How to change variable in a for loop in Python?

My code:

for x in remove_zeros:
    if x == remove_zeros[-1]:
        x = '0' + x
    else:
        x = '1' + x

For some reason this does not do anything to the variables. I've looked up how to fix this, and nothing works at all. Basically, I'm detecting if an element in a list is the last element or not, and then if it is, I'm either adding a 0 or a 1 in front of it. I cannot figure out how to make this work.

When you write x = '0' + x , you simply overwrite the value to which the name x points to. You do not directly modify the value inside the list that x was originally pointing to with each new execution of the for x in remove_zeros: loop.

You can modify the value inside the list by accessing it directly with its index and assigning a new value to it. An easy way to do this is with enumerate , which loops over the list indices and values at the same time:

 for index, x in enumerate(remove_zeros):
            if x == remove_zeros[-1]:
                remove_zeros[index] = '0' + x
            else:
                remove_zeros[index] = '1' + x

In a for loop, the control variable (x) is a temporary variable that is reassigned at every iteration. In the case of strings, it is not a reference to the element of your list but a separate copy. This means that changing x inside the loop will have no effect on the list.

Given that you are modifying every element in the list, you can do this without resorting to indexes (which is not very Pythonic). Try producing a new list using a list comprehension:

remove_zeros = [ '10'[x==remove_zeros[-1]]+x for x in remove_zeros ]

Use index numbers instead of a temporary variable x to modify the value of a list:

for i in range(len(remove_zeros)):
  remove_zeros[i] = ('0' if remove_zeros[i] == remove_zeros[-1] else '1') + remove_zeros[i]

You are changing x transiently during each iteration of the loop, but these changes are not being saved anywhere. Every time the loop repeats x is redefined to be the next element in the list and the modification you have made is lost.

Instead, overwrite the existing list elements with your desired values. One way to do this is using enumerate :

 for n,x in enumerate(remove_zeros):
    if x == remove_zeros[-1]:
        remove_zeros[n] = '0'+x
    else:
        remove_zeros[n] = '1'+x

for loop control variable is not a reference to an element of the list, it is a copy of an element. Changing it won't change the element of the list. You can either store your results in another list:

result = []
for x in remove_zeros:
    if x == remove_zeros[-1]:
        result.append('0' + x)
    else:
        result.append('1' + x)

or do what @jfaccioni suggested. BTW, either way you're not checking if x is the last element of the list, but whether x is equal to the last element. Consider a list: ['3','0','1','2','3'] … you'll prepend 0 to both 3 s in the list.

It is because you're working on your loop variable x and not on the actual element you want to change. The element in remove_zeros stays untouched. Change your code to something like:

for i in range(len(remove_zeros)):
    remove_zeros[i] = '0' + remove_zeros[i] if remove_zeros[i] == remove_zeros[-1] else '1' + remove_zeros[i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM