TUPLES IN PYTHON


In this tutorial, we are going to learn about tuples in python and how it is different from lists in python, further we learn about looping tuples, adding items to a tuple and deleting items from it and changing items in it as well.


What are Tuples in Python?

Using Python Tuple, the sequence of immutable python objects is stored. Tuple is similar to lists since it is possible to change the value of the items stored in the list while the tuple is immutable and it is not possible to change the value of the items stored in the tuple.

Tuples in Python

A tuple comprises of set of comma-separated objects encapsulated inside the parentheses. The following can be described as a tuple:

tuple1 = (230, "James", 123)   
tuple2 = ("red", "green", "blue")

Using a For Loop in Tuples

You can also iterate a tuple using a for loop.

tuple= ("apple", "orange", "lemon") for n in tuple: print(n)

Adding Items to Tuple

Since Tuples are immutable meaning that you cannot add the values to a tuple once it is created just like it is possible in lists. For Example:

tuple1= ("apple", "orange", "lemon") 
tuple1[3] = "banana"
 
# It's an error 
print(tuple1)

banana won’t be created as a new element since tuple doesn’t support it. Hence, the output will be:

Traceback (most recent call last): File "/tmp/sessions/4ee7c8963287ca22/main.py", line 2, in  tuple1[3] = "banana" TypeError: 'tuple' object does not support item assignment




Deleting a Tuple

You cannot delete items inside a tuple, however you can delete the whole tuple. For example:

tuple1= ("apple", "orange", "lemon") 
del tuple1 
print(tuple1)

Once the tuple is deleted then the items inside it won’t be recalled therefore, producing this error:

Traceback (most recent call last):
  File "/tmp/sessions/550f21853aa12970/main.py", line 3, in 
    print(tuple1)
NameError: name 'tuple1' is not defined

Negative Indexing in Tuple

Just like lists, tuples also have negative indexing starting from the most right (-1) to the most left. For Example:

tuple1= ("apple", "orange", "lemon") 
print(tuple1[-1])

Output will be:

lemon

Changing Tuple Values

As we know that tuples are immutable, means that we cannot change the values inside a tuple. However, we can convert a tuple into a list and then change the values of that list and again change the particular list into a tuple again. For Example:

tuple1= ("apple", "orange", "lemon") 
tuple2 = list(tuple1) 
tuple2[1] = "banana" 
tuple1 = tuple(tuple2) 
print(tuple1)




We were able to convert the tuple into a list by using the list() constructor and later we converted the list into a tuple again by using the tuple() constructor. Output will be:

('apple', 'banana', 'lemon')

For more reference, click here