1

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"]
agp22888
  • 25
  • 4
  • 5
    Why not just concatenate the lists with `+`? Or you could use [`itertools.chain`](https://stackoverflow.com/a/953097/8204776). – meowgoesthedog Jan 28 '19 at 11:43
  • 4
    You can do this (but probably shouldn't): `t2 = ["1", "2", *[x for x in t], "6", "7"]` You could also just use `t2 = ["1", "2", *t, "6", "7"]` if you had no processing to do. – Mark Jan 28 '19 at 11:45
  • 3
    @MarkMeyer It's fine to do that, I think. But it doesn't work in older python versions. And using a generator expression is sligthly more efficient, since you don't need to allocate memory for a temporary list. `["1", "2", *(x for x in t), "6"]` or simply `["1", "2", *t, "6"]` – Håken Lid Jan 28 '19 at 11:52
  • @meowgoesthedog you're right, in my example it's easier to use concatenation, but in real task first list is not a list, it's a django queryset. Yes, querysets can be converted to list using list(t.values_list('field_name', flat = True)), but I was looking for more "elegant" way... – agp22888 Jan 28 '19 at 12:24

1 Answers1

3

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"]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 2
    Note that unpacking in list literals was added in python 3.5, so if you are using an older python version, you will have to concatenate lists using `+` instead. – Håken Lid Jan 28 '19 at 11:54