You have a list l
that contains exactly one element (and this element happens to be another list, but that's not highly relevant here), therefore:
l[0] # WORKS: this is the first item in the list
l[1] # INVALID: there is no item here, so it raised an IndexError
This is the basic answer that everyone else is saying, and I'm just trying to say it very clearly. Note, specifically, that Python lists are indexed with the first element at 0
rather than 1
, so a list of length 1 will only have a single element at index 0.
A way that you could have more easily identified the problem yourself would have been to split the compound line you use into two lines -- this is a common method of debugging which is generally very useful:
# l[1].append(x) # doing two things in the same line (accessing and element, and then appending)
temp = l[1]
temp.append(x)
Here the traceback will point more clearly to the problem.
(As an aside, I disagree with dpkp's suggestion of using a "defaultlist" since I think it's an overly complicated, non-standard, and advanced solution to a beginner problem. Instead, if you want a workaround to this problem where a list is automatically created to append to, please post that as a separate question with more specifics about why you want it -- and I think you'd probably want a defaultdict using integer keys, but that should wait for the full question.)