Reputation: 83
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
Upvotes: 1
Views: 142
Reputation: 17322
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)
Upvotes: 1
Reputation: 42778
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
]
Upvotes: 3