Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a fixed-length Python list by variable number of characters?

(If someone can suggest a better title, by all means go ahead and edit).

Given a list list1 whose exact length is unknown but for which it is known will always be less than or equal to 5, I'm looking to populate a separate empty list list2, of fixed length 5, with the values in list1, padding out with empty strings if the size of list2 is less than 5.

e.g. if list1 = [1,2,3]

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

and so on.

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's the neatest way of achieving this (determining how many empty strings to add)?

like image 268
Pyderman Avatar asked Oct 09 '15 05:10

Pyderman


1 Answers

list2 = list1 + [''] * (5 - len(list1))
like image 194
jfs Avatar answered Oct 05 '22 01:10

jfs