Tuples are another one of the 4 in-built data types in Python. They are very similar to lists but have some notable differences. This post will cover the features of Tuples that are different from that of lists. For the similar features, you can refer to the two part series, Python Lists Part-1 and Python Lists Part-2
Tuples are immutable
This means that unlike lists, we cannot change, add or remove items from a 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-
x = ("red",) #Note the comma after the element
print(x)
#Not a tuple
y = ("red")
print(y)
The tuple constructor
Any data type can be converted into a tuple by using the tuple() constructor.
For example-
x = tuple(("red", "green", "blue")) #Note the double brackets
print(x)
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)
The 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)
The 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)
The output:
green
Joining Tuples
You can add tuples using the + operator. For example;
tuple1=("red","green")
tuple2=("blue","yellow")
tuple3= tuple1+tuple2
print(tuple3)
The output-
Multiplying Tuples
You can multiply tuples using the * operator. For example;
x = ("a", "b")
y = x*2
print(y)
The output-
("a", "b", "a", "b")
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