Hafees Kazhunkil
Hafees Kazhunkil

Reputation: 113

How to get the expected result using list comprehension

I have the following lists

a=[1,2,3]
b=[4,5,6]
c=[a,b]

i need to combine both list a and b.

result should be like [1,2,3,4,5,6]

i tried with list comprehension

[x for x in i for i in c]

output

[3, 3, 4, 4, 5, 5]

How can i get the result as [1,2,3,4,5,6] using list comprehension.

Upvotes: 0

Views: 58

Answers (5)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

You are concatenating, use + to do so:

c = a + b

If you are concatenating an arbitrary number of lists, use itertools.chain.from_iterable():

from itertools import chain

list_of_lists = [a, b]
c = list(chain.from_iterable(list_of_lists))

Note that if all you need to do is iterate over the concatenation result, you can leave of the list() call altogether.

Do not use sum() for this; that leads to quadratic behaviour as intermediate results are built for every element summed, which takes a full loop.

Upvotes: 1

heemayl
heemayl

Reputation: 41987

You can just do:

a + b

If you must use list comprehension:

In [10]: a = [1, 2, 3]

In [11]: b = [4, 5, 6]

In [12]: c = [a, b]

In [13]: [j for i in c for j in i]
Out[13]: [1, 2, 3, 4, 5, 6]

Upvotes: 1

riteshtch
riteshtch

Reputation: 8769

Here are 3 different ways you can do it:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6]
>>> c=[item for l in [a, b] for item in l]
>>> c
[1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain(*[a, b]))
[1, 2, 3, 4, 5, 6]

Upvotes: 0

user5547025
user5547025

Reputation:

Use itertools.chain.

import itertools

a=[1,2,3]
b=[4,5,6]

c = list(itertools.chain(a, b))

Upvotes: 1

cmashinho
cmashinho

Reputation: 615

You can do it with + operation

a = [1, 2, 3]
b = [3, 4, 5]
c = a + b # Equal [1, 2, 3, 3, 4, 5]

Upvotes: 0

Related Questions