Sobes.tech
Junior — Middle

Is it possible to insert a new element at the end of a tuple in Python?

sobes.tech AI

Answer from AI

In Python, tuples (tuple) are immutable data structures, so you cannot insert a new element directly into an existing tuple.

However, you can create a new tuple by concatenating the old one with a new element:

old_tuple = (1, 2, 3)
new_element = 4
new_tuple = old_tuple + (new_element,)
print(new_tuple)  # (1, 2, 3, 4)

Thus, you are not actually modifying the original tuple, but creating a new one with the added element.