简体   繁体   中英

Python append to list of lists

I'm trying to simply append to a list of lists but cannot find a clean example of how to do that. I've looked at dozens of examples but they are all for appending to a one-dimensional list or extending lists.

Sample code:

testList = []
print(testList)
testList.append(3000)
print(testList)
testList[3000].append(1)
testList[3000].append(2)
print(testList)

Expected result:

testList[3000][1, 2]

Actual result:

[]
[3000]
Traceback (most recent call last):
  File ".\test.py", line 5, in <module>
    testList[3000].append(1)
IndexError: list index out of range

First, thank you to everyone for the quick responses. Several of you got me thinking in the right direction but my original question wasn't complete (apologies) so I'm adding more context here that's hopefully helpful for someone else in the future.

wp-overwatch.com jogged my memory and I realized that after working with only dictionaries in my application for days, I was treating the "3000" like a dictionary key instead of the list index. ("3000" is an example of an ID number that I have to use to track one of the lists of numbers.)

I couldn't use a dictionary, however, because I need to add new entries, remove the first entry, and calculate average for the numbers I'm working with. The answer was to create a dictionary of lists.

Example test code I used:

testDict = {}
blah10 = 10
blah20 = 20
blah30 = 30
blah40 = 40

exampleId = 3000

if exampleId == 3000:
    testDict[3000] = []
    testDict[3000].append(blah10)
    testDict[3000].append(blah20)
    print(testDict)
    testDict[3000].pop(0) # Remove first entry
    print(testDict)
    testDict[3000].append(blah30) # Add new number to the list
    average = sum(testDict[3000]) / len(testDict[3000])
    print(average)
if exampleId == 3001:
    testDict[3001].append(blah30)
    testDict[3001].append(blah40)

Result:

{3000: [10, 20]}
{3000: [20]}
25.0

list.append adds an object to the end of a list. So doing,

listA = []
listA.append(1)

now listA will have only the object 1 like [1]. you can construct a bigger list doing the following

listA = [1]*3000

which will give you a list of 3000 times 1 [1,1,1,1,1,...].

If you want to contract a c-like array you should do the following

listA = [[1]*3000 for _ in range(3000)]

Now you have a list of lists like [[1,1,1,1,....], [1,1,1,....], .... ]

PS Be very careful using [1]*3000 which in this case works but in case you use it with a variable it will have side effects. For example,

a = 1
listA = [a]*3000

gives you the same result but if any of the variables 'a' change then all will be changed the same way.

The most safe is, using list comprehensions

a = 1
listA = [a for _ in range(3000)]

In order to update any value, just do the following,

listA[656] = 999

Lastly, in order to extend the above list just type

listA.append(999)

and then at the index 3000 (starting from zero) you will find 999

testList[3000].append(1) is telling Python to grab the 3000th item in the list and call the append function on it. Since you don't have 3000 items in the list, that's why you're getting that error.

If you want to lookup an item by a value such as 3000 instead of by its position in the list, then what you're wanting is not a list but a dictionary .

Using a dictionary you can do:

>>> testList = {} # use curly brackets for a dictionary
>>> print(testList)
{}
>>> testList[3000] = [] # create a new item with the lookup key of 3000 and set the corresponding value to an empty list
>>> print(testList)
{3000: []}
>>> testList[3000].append(1)
>>> testList[3000].append(2)
>>> print(testList)
{3000: [1, 2]}
>>>

The first problem I see is that when you call testList.append() you are including the [3000] . That is problematic because with a list, that syntax means you're looking for the element at index 3000 within testList . All you need to do is call testList.append(<thing_to_append>) to append an item to testList.

The other problem is that you're expecting [1, 2] to be a separate list, but instead you're appending them each to testList .

If you want testList to be composed of multiple lists, a good starting point would be to instantiate them individually, and to subsequently append to testList. This should help you conceptualize the nested structure you're looking for.

For example:

testList = []
three_k = [3000]
one_two = [1, 2]

testList.append(three_k)
testList.append(one_two)

print(testList)

From there, the you can actually use the indexes of the nested lists to append to them. So if [3000] is the list at index 0 (zero), you can append to it by doing: testList[0].append(<new_append_thing>) .

It is because according to your program the python interpreter will look for the 3000 index at the list and try to append the given number in the index of 3000 but there is not that number so it will print error.

To fix it:

testList = []
print(testList)
testList.append(3000)
print(testList)
testList.append([1])
testList[1].append(2)
print(testList)

Using the index you can append the value as I appended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM