AppDividend
Latest Code Tutorials

How to Append an Element to Tuple in Python

Python tuple is an unordered, immutable data type that is used to store collections. Tuple data types are initialized by encapsulating values using parentheses ().

Python tuple append

Appending a tuple in Python is not possible because it is an immutable object. But there is another way in which you can add an element to a tuple.

To append an element to a tuple in Python, follow the below steps.

  1. Convert tuple to list using the list() method.
  2. Append element to the list.
  3. Convert the list to a tuple.

Step 1: Convert tuple to list

To convert a tuple to a list in Python, use the list() method.

tup = (11, 21, 19, 18, 29)

lst = list(tup)

print(lst)
print(type(lst))

Output

[11, 21, 19, 18, 29]
<class 'list'>

You can see that list() method converted tuple to list. The type() is a built-in function that allows you to check the data type of the parameter passed to it.

Step 2: Append an element to the list

To append an element to a list in Python, use the append() method.

tup = (11, 21, 19, 18, 29)

lst = list(tup)

lst.append(46)

print(lst)

Output

[11, 21, 19, 18, 29, 46]

And we appended the “46” element to the list.

Step 3: Convert a list to tuple.

To convert a list to a tuple, use the tuple() function.

tup = (11, 21, 19, 18, 29)

lst = list(tup)

lst.append(46)

tup = tuple(lst)

print(tup)

Output

(11, 21, 19, 18, 29, 46)

And we successfully append an element to a tuple using the conversions and append() method.

That’s it for the Python tuple append tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.