Reputation: 9205
In Javascript, I can do something like this
let list = [1, 2, 3]
let list2 = [4, 5, 6, ...list]
And the resulting list would be [4,5,6,1,2,3]
Is there a way to do this in Python without having to call extend()
or using +=
after declaring the list?
Upvotes: 1
Views: 47
Reputation: 155418
The additional unpacking generalizations of PEP 448 (added in Python 3.5) allows the following syntax:
list2 = [4, 5, 6, *list]
The elements of the first list
are unpacked, one after another, in the same order they appear in the original list
.
Prior to 3.5, the best solution is just:
list2 = [4, 5, 6] + list
which is still a one-liner, but has to construct the temporary list
first, then concatenate the two of them and throw away the temporary.
Upvotes: 3