12

This sounds like a super easy question, so I'm surprised that searching didn't yield any results: I want to initialize a list of constants and extend it with a list from another source.

This works:

remoteList = [2, 3, 4]
myList = [0,1]
myList.extend(remoteList)

Which means it gives the expected results:

myList
[0, 1, 2, 3, 4]

However, doing the list initialization in one line doesn't work, myList is left undefined:

remoteList = [2, 3, 4]
myList = [0,1].extend(remoteList)

Is there a way to initialize the list and extend it with another list (in a pythonic way) in one line? Why doesn't my one line example work, or at least produce some sort of list?

Casey
  • 475
  • 6
  • 19
  • 2
    Why do you think that being able to write something in one line makes it more pythonic? – poke Jan 03 '18 at 23:28
  • @poke that's a good question: In this case it's more about doing the initialization all at once (in one line) rather than breaking it up. It feels more accurate to have one statement (in one line) that says: this is my list. – Casey Jan 03 '18 at 23:35

3 Answers3

16

You can use unpacking inside the list literal

myList = [0, 1, *remoteList]

This is part of the unpacking generalizations made available in Python 3.5

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
9

Are not you just asking about the + list concatenation operation:

In [1]: remoteList = [2, 3, 4]

In [2]: myList = [0, 1] + remoteList

In [3]: myList
Out[3]: [0, 1, 2, 3, 4]

Works for both Python 2 and 3.


There are some slight differences between "extend" and "plus":

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1
a = [2,3,4]
b = [1,2] + a  # will add the other list
print( b)

Output:

[1, 2, 2, 3, 4]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69