1

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
2

2 Answers 2

3

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
    ]
Sign up to request clarification or add additional context in comments.

1 Comment

Could you also please add an information why the error happened?
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.