简体   繁体   中英

List comprehension appending twice to same list does not work

I'm try to append to a single list twice using two list comprehension. My code is like below:

list_one = [1, 2, 3]
list_two = [4, 5, 6]

list_a = []
list_b = []

list_a = [ x for x in list_one ]
list_a = [ x for x in list_two ]

for i in list_one:
    list_b.append(i)

for i in list_two:
    list_b.append(i)

print(f"list_a: {list_a}")
print(f"list_b: {list_b}")

Script Output:

list_a: [4, 5, 6]
list_b: [1, 2, 3, 4, 5, 6]

How can I make all values appended into list_b using list comprehension?

Because you overwrote list_a .

Try:

list_a = []
list_a += [ x for x in list_one ]
list_a += [ x for x in list_two ]

or

list_a = []
list_a.extend(x for x in list_one)
list_a.extend(x for x in list_two)

I assume that the example list comprehension was simplified .
If it was actual code, you can do just:

list_a = list_one + list_two

You can use a nested comprehension:

>>> list_b = [x for l in (list_one, list_two) for x in l]
>>> list_b
[1, 2, 3, 4, 5, 6]

or use a utility like itertools.chain or simple concatenation:

list_b = list(chain(list_one, list_two))
list_b = list_one + list_two

I think this is what you are trying to do...

list_one = [1, 2, 3]
list_two = [4, 5, 6]
list_one.extend(list_two)#[1, 2, 3, 4, 5, 6]
list_two=list_one##[1, 2, 3, 4, 5, 6]

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