This is a detailed tutorial on Python Tuples. Learn to create tuples, store data in them, and perform different operations using various methods.
There are several different python data types to store a collection of data and tuples are one of them. A tuple is basically an ordered collection and it is immutable. In other words, once the elements of the tuples are defined, they can not be changed and no new elements can be added.
The syntax to create a tuple is given below. You have to write all the tuple elements separated by commas inside the parenthesis.
aTuple = ("Tutorial","Lesson","Teaching") print(aTuple) print(type(aTuple))
Note. You can add elements of any data type inside a tuple. Even a tuple can contain a collection of elements that belongs to different data types.
Accessing Tuple Items
Tuple elements can be easily accessed using the square brackets index notation. You have to write the tuple name, immediately followed by square brackets containing the index of the tuple element that you want to access. The tuple elements index starts from 0.
Example. The following example fetches the tuple element at indexes 0, 1, and 2.
aTuple = ("Tutorial","Lesson","Teaching", 21) print(aTuple[0]) print(aTuple[1]) print(aTuple[2])
Accessing Tuple Items From the End
You can make use of the concept called negative indexing to fetch items, starting from the end of the tuple, rather than from the front. Therefore -1 indicates the index of the last tuple element and -2 indicates the index of the second last tuple element and so on you can find the index of any element from the end.
Example. In the following python code, we’re fetching the value of the last and second last item using the concept of negative indexing.
aTuple = ("Tutorial","Lesson","Teaching", 21) #Negative Indexing print(aTuple[-1]) print(aTuple[-2])
Fetching Multiple Tuple Items
You can use the concept called a Range of Indexes to fetch multiple tuple items. This can also be done in a simple way using a positive range of indexes and can also be done in a reversed way like negative indexing using the negative index of ranges. Here also you have to access the items using the square brackets notation.
But instead of writing a single index inside the brackets, you must write the starting index and the index of an element just after the ending element, both separated with a semi-colon. In other words, if you write 1:4, it will fetch the elements starting from index 1 up to 3. The element at the 4th index will not be included in the result.
Example. The following code illustrates how you can fetch multiple tuple items using a positive range of indexes and a negative range of indexes.
aTuple = ("Tutorial","Lesson","Teaching", 21, "Hello", "Python") #Postive Range of Indexes print(aTuple[1:4]) #Negative Range of Indexes print(aTuple[-5:-2])
Make sure that the index range always starts from the left. In the above example, the range 1:4 will fetch the elements starting from index 1 up to 3 from the left. Even in the negative indexing, the range -5:-2 will return the elements starting from the 4th element from the end, not the fifth, and up to the first element from the end. Observe the output of the code carefully to understand how the concept of selecting a range of elements actually works in python.
Modifying Tuple Items
We know that tuples are immutable i.e. their items can not change once they are defined. Due to its unchangeable nature, you simply can not modify the tuple items by just using the tuple properties and methods. But there’s another thing that you can do to change the tuple values.
You can convert the tuple into an iterable data type that is not immutable and then you can change the item value there and then again can convert back the iterable data type into a tuple. The Python list is the perfect option for the iterable data type that is similar to a tuple and it is not immutable.
aTuple = ("Tutorial","Lesson","Teaching", 21) #Converting Tuple To List aList = list(aTuple) #Modify Items aList[1] = "Hello" aList[2] = "Good" #Converting List Back to Tuple aTuple = tuple(aList) #Modified tuple print(aTuple)
Iterating a Tuple
You can easily loop through tuple items using a python for loop.
Example. In the following code, we’re looping through the tuple using the simple for-loop notation that we use often to loop through any other iterable.
aTuple = ("Tutorial","Lesson","Teaching", 21) for item in aTuple: print(item)
Checking If Items Exist in the Tuple
Membership operators in and not in can be used to check if a particular item exists in the tuple or not.
Example. The following code makes use of the in operator with an if-else statement to find if the element is there is the tuple or not.
aTuple = ("Tutorial","Lesson","Teaching", 21) if "Tutorial" in aTuple: print("Yes, this item is there in the tuple.") else: print("No, this item is not there in the tuple.")
Find the Length of a Tuple
The function len()
can be applied to any of the python objects to find the number of items present in a particular tuple. We’ve also illustrated in a separate article how you can do the same with a list. (Python List Size)
Example. In the following snippet of code, the function len()
has been used to find the length of the tuple stored in the variable aTuple
.
aTuple = ("Tutorial","Lesson","Teaching", 21) length = len(aTuple) print(length)
Adding Items to a Tuple
Again as Tuples are immutable, new items can not be added to them. So, if you will even try to add an element to a tuple using any method, it will raise an error. But as earlier in this article, I told you the way of converting the tuple into a list first and then changing the value, and then again converting the list back to the tuple, this method can also be used to add new items to a tuple.
Example. The following code illustrates the same.
aTuple = ("Tutorial","Lesson","Teaching", 21) #Tuple To List aList = list(aTuple) #Appending New Item to List aList.append("Hello") #List To Tuple aTuple = tuple(aList) print(aTuple)
Here we’ve first converted the tuple into a list and then using the List append method we’ve added the new item then again using type conversion, we’ve converted the list back into the tuple.
Single Item Tuple
In most of the python iterable objects, you are able to have a single item. Even in a tuple, you can have only one item, but there’s a slight difference in defining a tuple with a single item. As we know we have to separate the different tuple items in parenthesis using commas. And as we know if we’ve to define only one item we need not add any separation symbols like commas for most of the other tables in python, like a Python List.
But in a tuple, you must use the comma even if you’re adding only one item. If you will not add the comma after the single item of the tuple, it will consider it as a string rather than a tuple.
Example. The following code illustrates the right way of creating a single-item tuple.
#Wrong way creates a string rather than a tuple aTuple = ("Tutorial") print(type(aTuple)) #Right way to define a tuple with a single item aTuple = ("Tutorial",) print(type(aTuple))
I’ve used the type function in both of the cases to show that if you will not add the comma, the data type will be considered as a string rather than a single-item tuple.
Deleting Tuple and Tuple Items
Again due to the immutable nature, you can not delete items of a tuple directly. But you can use the way of the tuple to list conversion, doing the deletion, and then again list to-tuple conversion for the same. To delete the tuple, the keyword del
can be used.
Example. Here, we’re deleting a tuple item and then deleting the entire tuple.
aTuple = ("Tutorial","Lesson","Teaching", 21) #Tuple To List aList = list(aTuple) #Removing Item aList.remove("Teaching") #List To Tuple aTuple = tuple(aList) print(aTuple) print("\nITEM DELETED SUCCESSFULLY!\n") #Deleting Tuple del aTuple #Trying to print, but it won't. ERROR! print(aTuple)
Merge Multiple Tuples
The operator +
can be used to merge two or more tuples. Although, the tuples are immutable yet they can join with each other!
Example. We’re merging three different tuples with different data types.
tuple1 = ('a','e','i','o','u') tuple2 = (1,2,3,4,5) tuple3 = (True, False, [1,2], {"Hello" : "Hi!"}) #Joining Tuples mergedTuple = tuple1 + tuple2 + tuple3 print(mergedTuple)
tuple()
Constructor Method
You can convert any Python iterable into a tuple using the constructor method tuple().
Example. In the following demonstration, we’re converting a python list into a tuple using the tuple() constructor.
hello = [1,2,3,4,5] print(type(hello)) print(hello) hello = tuple(hello) print(type(hello)) print(hello)
count()
Method
The tuple count()
method returns the number of times a particular element appears in the tuple.
Example. We’re checking how many times the element “Hello”, appears in the tuple using the method count()
.
aTuple = ["Hi","Hello","Bye!","Hello"] countHello = aTuple.count("Hello") print(countHello)
index()
Method
The method index()
returns the numerical index of a particular element in the tuple. It is similar to the index() method of Python List.
Example. We’re finding the index of the elements “Hi” and “Hello” using the tuple method count()
.
aTuple = ["Hi","Hello","Bye!","Hello"] print(aTuple.index("Hi")) print(aTuple.index("Hello"))
As the element “Hello”, appears twice in the tuple, therefore there are two indexes for it, 1 and 3. But remember that the index() method will only return the numerical index of the first occurrence of that particular element as shown in the following output screenshot as well.