Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a list in a list in Python

I'm so new to Python that the only way I can code so far is by blindly waving my keyboard around. So I'm sure there's an excellent reason why the following doesn't work:

l = []

grouping = compactlist.index(namelist[n])
l[grouping].append(start[n])
l[grouping].append(end[n])

So what I'm trying to do is take a value from the start list and add it to a list in l - which list it'll be is dependendent on the value of grouping. (Then do the same for end). This requires the lists within l to be created on the fly, which I assume is the problem.

like image 769
lowercasename Avatar asked Feb 22 '23 19:02

lowercasename


1 Answers

You could initiate l like l = [[], []], but it actually sounds more like you want to use a defaultdict as your data structure. This can create your lists on the fly, e.g.

>>> import collections
>>> thing = collections.defaultdict(list)
>>> thing[0].append('spam')
>>> thing[1].append('eggs')
>>> print thing
defaultdict(<type 'list'>, {0: ['spam'], 1: ['eggs']})
>>> thing[0]
['spam']
>>> thing[69]
[]
like image 106
wim Avatar answered Feb 26 '23 18:02

wim