简体   繁体   中英

How to Assign new value to a list that is in another list?

I tried the following python code to assign a new value to a list.

a,b,c=[],[],[]
def change():
    return [1]
for i in [a,b,c]:
    i=change()
print(a)

The output is [] , but what I need is [1]

What you're doing here is you're re-assigning the variable i within the loop, but you're not actually changing a , b , or c .

As an example, what would you expect the following source code to output?

a = []
i = a
i = [1]
print(a)

Here, you are reassigning i after you've assigned a to it. a itself is not changing when you perform the i = [1] operation, and thus [] will output. This problem is the same one as what you're seeing in your loop.

You likely want something like this.

a, b, c = (change() for i in (a, b, c))

Please refer to this answer for changing external list inside function.

In [45]: a,b,c=[],[],[]
    ...: def change():
    ...:     return [1]
    ...: for i in [a,b,c]:
    ...:     i[:]=change()
    ...: print(a)
    ...: print(b)
[1]
[1]

You created a variable called i, to it you assigned (in turn) a, then 1, then b, then 1, then c, then 1. Then you printed a, unaltered. If you want to change a, you need to assign to a. That is:

a = [1]

Part of your problem is inside your for loop. You are saying i = 1, but that is not connected to any list. Your for loop should look like this:

for i in [a, b, c]:
    try:
        i[0] = 1
    except IndexError:
        i.append(1)

You rather have to do this way:

a,b,c=[],[],[]
def change(p):
    p.append(1)
for i in [a,b,c]:
    change(i)
print(a)

You are only changing the variable i . You are not changing the original list variables: a, b, c .

In the For loop, the variable i is assigned with copy of reference of a, b, c . It is a different variable altogether. Changing the value of i , does not change the value of a, b, c .

If you want to actually change the value of a, b, c, you have to use the append method.

a,b,c=[],[],[]
def change():
    return [1]
for i in [a,b,c]:
    i.append(change())
print(a) 

for more information, read this stackoverflow answer on passing value by reference in python

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