Tuples are another one of the 4 in-built data types in Python. They are very similar to lists but have some notable differences. In this post, I am going to tell about the features of Tuples that are different from that of lists. You can read about Python lists in the two part series, Python Lists Part-1 and Python Lists Part-2
Tuples are unchangeable
This means that we cannot change, add or remove items from the tuple once it has been created.
Creating a tuple with one item
The following method can be used to create a tuple with one item-
thistuple=("red",) #Note the comma after the element print(thistuple) #Not a tuple thistuple=("red") print(thistuple)
The tuple constructor
Any data type can be converted into a tuple by using the tuple() constructor. For example;
thistuple=tuple(("red","green","blue")) #Note the double brackets print(thistuple)
Accessing tuple items
Tuple items are accessed in the same way as list items. You can find the ways to access the items here.
Updating tuples
I have written above that tuples are unchangeable. This means that any new items can't be added or removed. However, there is a loophole. You can change the tuple into a list and change it and convert it back to a tuple. For example;
x=("red","green","blue") y=list(x) y[1]="yellow" x=tuple(y) print(x)
Output:
Adding items to a tuple
One way to add items to a tuple is by converting it into a list and using the .append function.
Another way to add elements to tuples is by adding another tuple to the tuple. For example;
thistuple=("red","green") y=("blue") print(thistuple+y)
Output:
Removing tuple items
Items can be removed from a tuple by using the same method of converting it to a list and using the .remove function.
Another way is by using the del keyword. For example;
thistuple=("red","green") del thistuple print(thistuple) #This will raise an error as the variable 'thistuple' no longer exists.
Unpacking a tuple
Assigning values to a tuple is known as packing. Similarly, in Python, we are also allowed to extract the values back into variables. This is called unpacking. For example;
thistuple=("red","green") (a,b)=thistuple print(a) print(b)
Output:
green
Joining Tuples
You can add tuples using the + operator. For example;
tuple1=("red","green") tuple2=("blue","yellow") tuple3= tuple1+tuple2 print(tuple3)
Output:
Multiplying Tuples
You can multiply tuples using the * operator. For example;
tuple=("a","b") tuple1=tuple*2 print(tuple1)
Output:
That is all for this post on Python Tuples. Hope you found it easy to understand. For any queries/suggestions, write a comment below or submit the contact form to the right hand side of the website.
Happy coding,
Aarav Iyer