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?
Since you want to associate an index (whether it exists or not) with an element of data, just use a dict with integer indexes:
>>> myParagraph={}
>>> myParagraph[0] = ''
>>> myParagraph[1] = 'this is the second line'
>>> myParagraph[2] = 'this is the third line'
>>> myParagraph[99] = 'this is the 100th line'
>>> myParagraph
{0: '', 1: 'this is the second line', 2: 'this is the third line', 99: 'this is the 100th line'}
Just know that you will need to sort the dict to reassemble in integer order.
You can reassemble into a string (and skip missing lines) like so:
>>> '\n'.join(myParagraph.get(i, '') for i in range(max(myParagraph)+1))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With