3

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

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use None type.

    >>> lst = [None] * 5
    >>> lst.append("a")
    >>> lst
    [None, None, None, None, None, 'a']

Comments

1

If you do [ [] ] * 10 the pointer will be copied to all items:

>>> a = [[]] * 10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> b = [ [] for i in range(10) ]
>>> b
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(5)
>>> a
[[5], [5], [5], [5], [5], [5], [5], [5], [5], [5]]
>>> b[0].append(5)
>>> b
[[5], [], [], [], [], [], [], [], [], []]

Comments

0

You can do:

l = [''] * 5
l.append('a')
print l

Comments

0

Remember that you can:

  1. multiply lists to repeat them (e.g. [1, 2] * 2 = [1, 2, 1, 2])

  2. add lists together (e.g. [1, 2] + [3, 4] = [1, 2, 3, 4])

Here is a suggested structure:

a = 'new item'
l = [''] * 5 + a
>>> l
['', '', '', '', '', 'new item']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.