Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initiliase list with empty elements python

Tags:

python

I am trying to initiliase a list with the first 5 elements empty and then append to the list thereafter. The purpose is that when i write this list to a csv file, the output will be as such: ,,,,,,a,b,c here is my code:

l = list()
l[:5]=""
l.append('a')

When i print out this list, it contains only the element 'a'. How can I initiliase the list such the first 5 elements are empty and when I print it out it will show something like [, , , , , 'a']

thanks

like image 804
snifferdog Avatar asked Feb 01 '26 01:02

snifferdog


1 Answers

For immutable types like string you can do -

lst = [""] * 5

Though doing this for mutable elements (like lists or so) can cause issues as all the five elements would be pointing to the same object , so mutating one of them would cause changes reflected in the other elements (as they are the same object) .

like image 54
Sharon Dwilif K Avatar answered Feb 03 '26 09:02

Sharon Dwilif K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!