Chamara Keragala
Chamara Keragala

Reputation: 5777

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?

Upvotes: 0

Views: 248

Answers (3)

Boseong Choi
Boseong Choi

Reputation: 2596

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

Upvotes: 1

Lakshmi Ram
Lakshmi Ram

Reputation: 11

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]

Upvotes: 0

user2390182
user2390182

Reputation: 73470

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

Upvotes: 0

Related Questions