For example:
tup = (1, 'a', 2, True)
I want to add one more element to the tup
at the end:
new_tup = (tup[0], tup[1], tup[2], tup[3], False)
Is there a more concise way to do this?
You can either concatenate tup
with a single element((False,)
) tuple or unpack the tup
into a new tuple with unpacking operator *
:
tup = (1, "a", 2, True)
new_tup1 = tup + (False,)
new_tup2 = (*tup, False) # You don't have to use parenthesis here.
print(new_tup1)
print(new_tup2)
output:
(1, 'a', 2, True, False)
(1, 'a', 2, True, False)
Note: You can only create new tuple objects as they are immutable objects you can't add or generally modify them in any way.
You can add tuples together which returns a single tuple of all the elements.
tup = (1, 'a', 2, True)
new_tup = tup + (False,) # put the False like this so it is a tuple to add to the previous.
Try this.
def addToTup(t, e):
return t + (e,)
tup = (1, 'a', 2, True)
d = addToTup(tup, False)
print(d)
Or you can use tup = tup.__add__((False,))