Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically extend a Python list to N elements if it's too short? [duplicate]

Tags:

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.

like image 844
Richard Fallon Avatar asked Dec 02 '19 00:12

Richard Fallon


People also ask

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

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)).

What is extend () method in list?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

How do you extend an empty list in Python?

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.

How do you repeat multiple elements in a list in Python?

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.


2 Answers

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 
like image 121
Dani Mesejo Avatar answered Oct 23 '22 23:10

Dani Mesejo


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.

like image 22
Steven Fontanella Avatar answered Oct 23 '22 22:10

Steven Fontanella