What is the best way in Python to automatically extend a list to N
elements, if the list has fewer than N
elements?
That is, let's have I have this string: s = "hello there"
. If I do this:
x, y, z = s.split()
I will get an error, because s.split()
returns a list of two elements, but I'm assigning it to 3 variables. What I want is for z
to be assigned None
.
I know I can do this the hard way:
l = s.split() while len(l) < 3: l.append(None) x, y, z = l
But there has to be something more elegant than this.
Python list extend() is an inbuilt function that adds the specified list elements to the end of the current list. The extend() extends the list by adding all items of the list to an end. For example: list1 = [1,2,3,4] , list2 = [5,6,7]; print(list2. extend(list1)).
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
You can add elements to an empty list using the methods append() and insert() : append() adds the element to the end of the list. insert() adds the element at the particular index of the list that you choose.
Using the * Operator 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.
If you want a one-liner, do:
s = "hello there" x, y, z, *_ = s.split() + [None, None, None] print(x, y, z)
Output
hello there None
Note that a one-liner is not necessarily more readable nor more elegant. A variation, thanks to @Grismar is:
x, y, z, *_ = s.split() + [None] * 3
extend
adds an iterable to the end of a list, so you can do:
l.extend(None for _ in range(3 - len(l))
or
l.extend([None]*(3-len(l)))
which is a bit more elegant but slightly slower because it needs to construct the list of Nones first.
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