agp22888
agp22888

Reputation: 25

Python: is it possible to use list comprehension inside list declaration?

Let's say I have a list:

t = ["3", "4", "5"]

Is it possible to include this list into another using list comprehension?
i.e.:

t2 = ["1", "2", x for x in t, "6", "7"]

with a result:

["1", "2", "3", "4", "5", "6", "7"]

Upvotes: 1

Views: 78

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20434

Yes, this is possible with star unpacking.

Consider,

[1, 2, *[3, 4, 5], 6, 7]

this unpacks the [3, 4, 5] list into the outer list due to the *.

Therefore you can equally use a list-comprehension in lieu of this.


I.e.

t = ["3", "4", "5"]
t2 = ["1", "2", *[x for x in t], "6", "7"]
#["1", "2", "3", "4", "5", "6", "7"]

Note that, in Python versions < 3.5, iterable unpacking is not implemented.

Therefore as an alternative, you can use basic concatenation with the + operator:

t2 = ["1", "2"] + [x for x in t] + ["6", "7"]

Upvotes: 3

Related Questions