Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a list and extend it with another list in one line? [duplicate]

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?

like image 822
Casey Avatar asked Jan 03 '18 23:01

Casey


People also ask

How do you extend the length of a list in Python?

extends() in Python extends() function takes an argument from the iterable (strin, list, tuple, set, dict) and add each elements at the end of the list. The length of the final list increases by the number of elements present in the iterable argument.

How do you repeat an element in a list?

The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.

How do you extend two lists in Python?

Join / Merge two lists in python using list. We can extend any existing list by concatenating the contents of any other lists to it using the extend() function of list i.e. # Makes list1 longer by appending the elements of list2 at the end. It extended the list_1 by adding the contents of list_2 at the end of list_1.


2 Answers

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

like image 164
Patrick Haugh Avatar answered Oct 26 '22 02:10

Patrick Haugh


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":

  • Concatenating two lists - difference between '+=' and extend()
like image 25
alecxe Avatar answered Oct 26 '22 00:10

alecxe