Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 663
F.S. Avatar asked Jan 20 '26 19:01

F.S.


2 Answers

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))
like image 152
dawg Avatar answered Jan 23 '26 10:01

dawg


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.

like image 44
Matthias Fripp Avatar answered Jan 23 '26 09:01

Matthias Fripp