How to expand a fixed-length Python list with a variable number of characters?

(If anyone can suggest a better headline, be sure to go ahead and edit).

Given list list1, whose exact length is unknown, but for which it is known, will always be less than or equal to 5, I want to populate a separate empty list list2 with a fixed length of 5, from the value in list1, filling in blank lines if the size of list2 is less than 5.

eg. if list1 = [1,2,3]

then list2 should be [1,2,3, '', '']

etc.

So:

 if len(list1) < 5: list2.extend(list1) # at this point, I want to add the empty strings, completing the list of size 5 

What is the easiest way to achieve this (determining the number of blank lines to add)?

+5
source share
2 answers
 list2 = list1 + [''] * (5 - len(list1)) 
+5
source

Another way:

 extend_list = lambda list, len=5, fill_with='': map(lambda e1, e2: e1 if e2 is None else e2, [fill_with]*len, list) print extend_list([1, 2, 3]) >>> [1, 2, 3, '', ''] print extend_list([1, 2], 3, '?') >>> [1, 2, '?'] 
0
source

Source: https://habr.com/ru/post/1233308/


All Articles