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
Alberto
  • 83
  • 2
  • 7
  • Please share the entire error message, as well as a [mcve]. Also, variable and function names should follow the `lower_case_with_underscores` style. – AMC Feb 16 '20 at 02:15
  • https://stackoverflow.com/questions/5653533/why-does-this-iterative-list-growing-code-give-indexerror-list-assignment-index – AMC Feb 16 '20 at 03:19

2 Answers2

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
    ]
Daniel
  • 42,087
  • 4
  • 55
  • 81
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)
kederrac
  • 16,819
  • 6
  • 32
  • 55