Skip to content
Advertisement

Extend Python list by assigning beyond end (Matlab-style)

I want to use Python to create a file that looks like

# empty in the first line
this is the second line
this is the third line

I tried to write this script

myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the third line'

An error is thrown: IndexError: list index out of range. There are many answers on similar questions that recommend using myParagraph.append('something'), which I know works. But I want to better understand the initialization of Python lists. How to manipulate a specific elements in a list that’s not populated yet?

Advertisement

Answer

You can do a limited form of this by assigning to a range of indexes starting at the end of the list, instead of a single index beyond the end of the list:

myParagraph = []
myParagraph[0:] = ['']
myParagraph[1:] = ['this is the second line']
myParagraph[2:] = ['this is the third line']

Note: In Matlab, you can assign to arbitrary positions beyond the end of the array, and Matlab will fill in values up to that point. In Python, any assignment beyond the end of the array (using this syntax or list.insert()) will just append the value(s) into the first position beyond the end of the array, which may not be the same as the index you assigned.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement