简体   繁体   中英

Problem with "list assignment index out of range" Python

I should replace the last element of a tuple in a list of tuples with and object given as input and I tried to write this code but I got a "list assignment index out of range" error at line 4. How should I fix it?

def replaceLast (tupleList, object):
    for i, tup in enumerate(tupleList):
        lis = list(tup)
        lis[-1] = object
        tupleList[i] = tuple(lis)
    return tupleList

lT=[(1,),(2,3),(),(7,3)]
replaceLast(lT,11) #=> [(11,), (2, 11), (11,), (7, 11)] -> this should be the result

The problem is the empty tuple in your list lT , which does not have a last element, therefore you cannot access it with lst[-1] .

Instead of changing lists, create new ones:

def replace_last(tuples, object):
    return [
        tup[:-1] + (object, )
        for tup in tuples
    ]

your issue is generated when you have empty tuple, then your variable lst will be an empty list so will not make sense to use lst[-1] , this will generate your error, a simple fix will be to check if is an empty list:

if lst:
    lst[-1] = object
else:
    lst.append(object)

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