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?
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.
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.
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.
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
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":
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With