Question

How can I use python3 variable expansion to add empty elements into a list.

>>> "a"*5  
'aaaaa'  

This initialises a list with 3 elements.

l = ['']  
>>> l  
['']  
>>> l.append('')  
>>> l.append('')  
>>> l  
['', '', '']

When I try to add 5 empty elements I get just one.

>>> l=['' * 5]  
>>> l  
['']  

I am writing this list into a csv, I want a cheap way to added empty columns, elements in a row. Where I build the row as elements in a list.

Was it helpful?

Solution

It was just a matter of semantics. Where I did the multiplication.

>>> l = [''] * 5  
>>> l  
['', '', '', '', '']  

or

>>> l=[]  
>>> l.extend([''] * 5)  
>>> l  
['', '', '', '', '']  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top