111

In JS I can do this

const a = [1,2,3,4]
const b = [10, ...a]
console.log(b) // [10,1,2,3,4]

Is there a similar way in python?

Alex Cory
  • 10,635
  • 10
  • 52
  • 62

3 Answers3

163

As Alexander points out in the comments, list addition is concatenation.

a = [1,2,3,4]
b = [10] + a  # N.B. that this is NOT `10 + a`
# [10, 1, 2, 3, 4]

You can also use list.extend

a = [1,2,3,4]
b = [10]
b.extend(a)
# b is [10, 1, 2, 3, 4]

and newer versions of Python allow you to (ab)use the splat (*) operator.

b = [10, *a]
# [10, 1, 2, 3, 4]

Your choice may reflect a need to mutate (or not mutate) an existing list, though.

a = [1,2,3,4]
b = [10]
DONTCHANGE = b

b = b + a  # (or b += a)
# DONTCHANGE stays [10]
# b is assigned to the new list [10, 1, 2, 3, 4]

b = [*b, *a]
# same as above

b.extend(a)
# DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh!
# b is too, of course...
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • is there a differencde between extend and []+[] – Tyler Cowan Jan 25 '18 at 20:25
  • @TylerCowan The former modifies one list and returns `None`, the latter returns a new list containing all the elements. Otherwise no. – Adam Smith Jan 25 '18 at 20:26
  • the last example only works on python3 – Julio Marins Jul 25 '18 at 18:46
  • the [] + [] takes more memory than .extend() because its a 2-step process – Mincho Dec 26 '21 at 16:09
  • 1
    @Mincho that's probably true, but maybe not for the reason you're thinking. Certainly not because it's a 2-step process. after `c = a + b` you have three lists, `a`, `b`, and `c`. Each one has to be held in memory until it falls out of scope (unless you `del a; del b`). After `a.extend(b)` you have only two lists -- `a` and `b`. That said: the biggest difference is still that `list.extend` mutates the existing list while `list.__add__` produces a new one. – Adam Smith Dec 26 '21 at 23:42
10

The question does not make clear what exactly you want to achieve.

To replicate that operation you can use the Python list extend method, which appends items from the list you pass as an argument:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]

If what you need is to extend a list at a specific insertion point you can use list slicing:

>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
5

Python's list object has the .extend function.

You can use it like this:

    a = [1, 2, 3, 4]
    b = [10]
    b.extend(a)
    print(b)
  • 3
    bah, I missed one ;) May be worth pointing out specifically that `list.extend` returns `None`, so not to use `b = b.extend(a)`. That's a common mistake from beginner Python users. – Adam Smith Jan 25 '18 at 20:25
  • 1
    @AdamSmith It's also worth knowing which types are mutable/immutable. In python, lists are mutable. –  Jan 25 '18 at 20:28
  • Good point, and one that was lacking from my own answer. Thanks! – Adam Smith Jan 25 '18 at 20:35