Alex Rivera | Logout

Python - How to change values in a list of lists?

Asked 2012-12-06T20:59:52.167
18

I have a list of lists, each list within the list contains 5 items, how do I change the values of the items in the list? I have tried the following:

    for [itemnumber, ctype, x, y, delay] in execlist:
        if itemnumber == mynumber:
            ctype = myctype
            x = myx
            y = myy
            delay = mydelay

Originally I had a list of tuples but I realized I cant change values in a tuple so I switched to lists but I still cant change any of the values. If I print ctype, x, y, delay, myctype, myx, myy, or mydelay from within the for loop it appears that everything is working but if I print execlist afterwards I see that nothing has changed.

Edit
Report

1 Answer

0

Changing the variables assigned in the for does not change the list. Here's a fairly readable way to do what you want:

execlist = [
    #itemnumber, ctype, x, y, delay
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
]

mynumber, myctype, myx, myy, mydelay = 6, 100, 101, 102, 104

for i, sublist in enumerate(execlist):
   if sublist[0] == mynumber:
        execlist[i] = [mynumber, myctype, myx, myy, mydelay]

print execlist

Output:

[[1, 2, 3, 4, 5], [6, 100, 101, 102, 104], [11, 12, 13, 14, 15]]
answered 2012-12-06T21:21:13.967

Your Answer