1

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?

S.B
  • 13,077
  • 10
  • 22
  • 49
marlon
  • 6,029
  • 8
  • 42
  • 76

3 Answers3

1

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.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

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.
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
0

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,))

codester_09
  • 5,622
  • 2
  • 5
  • 27