In this tutorial, we will acquire the knowledge of Python Tuple with the help of examples.
More precisely, we will understand on what is tuple, how to create, where and when to use it, and the possible operations that we can perform on the tuple.
Similar to a list, a tuple is a finite ordered sequence or collection of objects or data values called items or elements. It is a linear data structure in Python in which items are stored in a linear order one after another.
Unlike a list, a tuple is an immutable data type, which means that we won’t be able to change its items once it is created. That is, once a tuple is created, we cannot change or update its data values.
On the other hand, list is mutable data type, meaning that we can change values in the list once created it. This is main difference between a tuple and list.
So, we can say that tuple works in a similar fashion as a list but we cannot update value in the tuple while we can it in the list. So, we only use tuple data structure when we do not want to update the values of the tuple.
Hence, the complete definition of a tuple is:
A tuple in Python is a linear data structure that consists of a finite order sequence of immutable, heterogeneous data elements that are of fixed sizes. It is a class in Python that’s stored on the heap and is overhead on the garbage collector.
How to create Tuple in Python
We can create a tuple in Python by placing all the objects (elements) inside parentheses (), separated by a comma (,). However, the parentheses are optional but it is good practice to write it.
Each element has a location index range from 0 to n – 1 where n is the total number of elements in the tuple. The general syntax to create a tuple in Python programming language is as:
tuple_name = (element_1, element_2, element_3, . . . , element_n) Or, tuple_name = (value1, value2, value3, . . ., valuen)
In the above syntax, tuple_name is the name of tuple and value1, value2, . . ., valuen are the values or elements assigned to the tuple. Let us a simple example of creating a numeric tuple.
# Creating a numeric tuple. data = (2, 4, 6, 8, 10, 12, 14, 16)
Here, data is the name of tuple and 2, 4, 6, 8, 10, 12, 14, 16 are the sequence of values or elements assigned to the tuple. Look at the below figure to understand how elements are indexed in the tuple.
We can access each element in the tuple by using the tuple name followed by a unique index or subscript that specifies the location of the element in the tuple. Each element has a unique index position in the tuple.
The index of the first element begins from 0, index of the second element is 1, and so on. In the above figure, the value 2 is stored in the index 0, value 4 stored in the index 1, value 6 stored in the index 2, and so on.
Creating Tuples in Python with Examples
1. Example: Creating an empty tuple:
# Zero element tuple. my_tuple = () print(my_tuple)
In this example, we have created a tuple with zero elements. This is an empty tuple. To create an empty tuple, use only two parentheses ().
2. Example: Creating a numeric tuple:
# Five elements tuple. my_tuple = (23, 25, 27, 29, 31) # for integer values print(my_tuple) # displaying contents of my_tuple.
Output: (23, 25, 27, 29, 31)
In this example, we have created a tuple with a sequence of numbers and assigned it to a variable named my_tuple. Then, we have displayed the values of tuple by passing my_tuple to the print() function.
The values and order of elements in the tuple are the same as they were when the tuple was built. Note that there is no need to include a comma at the end.
As you see in the output, Python always enclosed tuples in parentheses, so that they are interpreted precisely. Let us move on to create a tuple with a sequence of string elements.
3. Example: Creating a string tuple
# Creating a tuple with a sequence of four elements of string type. my_tuple = ("John", "Bob", "Harry", "Mark") # for string values # Displaying the contents of tuple. print(my_tuple)
Output: ('John', 'Bob', 'Harry', 'Mark')
4. Example: Creating a mixed data type values
my_tuple = ("Scientech", "Easy", 12, 15,5) # for mixed datatype values print(my_tuple)
Output: ('Scientech', 'Easy', 12, 15, 5)
5. Example: Creating a nested tuple
my_tuple = ("Python", (5, 15, 20), [2, 1, 4]) # for nested tuple print(my_tuple)
Output: ('Python', (5, 15, 20), [2, 1, 4])
In this tuple, there are three elements; first is “Python”, second is tuple, and third is list. The element tuple consisting of three elements is considered as a single element. Similarly, list consisting of three elements are also considered as a single item in the tuple.
6. Example: Creating a tuple without the parentheses
my_tuple = "Python", 2, 3.5, (5, 15), [2, 4] # without parentheses print(my_tuple)
Output: ('Python', 2, 3.5, (5, 15), [2, 4])
7. Example: Creating a tuple with one element
To create a tuple with a single element, you need to include a comma after element value, as mentioned below:
my_tuple = (20,) # creating a tuple with single value. print(my_tuple)
You cannot create a tuple if you forget to include a comma. For example, the following code merely assigns the integer value 20 to the variable num.
num = (20) # creates an integer.
If you forget to include a comma after element, then tuple will automatically get converted to string, integer or decimal data type.
Features of Tuple in Python
A tuple is a sequence data structure in Python programming language that provides almost all the functionalities offered by the array data structure. There are the following features or characteristics of tuples in Python. They are as:
1. Linear data structure: A tuple is a linear data structure in which Python store elements of a tuple in the contiguous memory locations in a linear order one after the other.
2. Ordered: A tuple is an order collection of elements. It preserves our insertion order in which we have placed elements in the order.
3. Duplicate elements: A tuple allows any number of duplicate elements or items.
4. Immutable: In Python, tuple is an immutable data type, meaning we cannot make an update or change in the existing tuple object. It provides a security to the data values. If we attempt to change or update the existing tuple, then this operation will raise an error.
5. Speed: As tuples are immutable in nature, iterating over elements of tuples is faster than lists. Therefore, there is also a slight performance boost.
6. Declaration: Declaration of tuples in Python is quite easy because we do not need to declare the tuple object before using it. When we assign values in the parentheses (), the tuples automatically declared.
7. Heterogeneous elements: One of the biggest advantages of using a tuple in Python is that we can construct a tuple of heterogeneous elements. In simple words, it can hold elements of different types and can have as many elements as we want subject to the availability of computer memory.
We can insert elements or values of different data types, such as string, numbers, object, or even another tuple as an element, etc. in a single tuple. The elements of different data types take the memory space in the computer in accordance with the value of a particular type stored in the tuple.
8. Functionality: Python tuple date type provides many functions that allow us easily to perform different set of operations instead of writing long code from scratch. We can use dir(tuple) to gain a list of functions provided by a list. For example:
# Getting a list of functions provided by Python tuple print(dir(tuple))
Output: ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
9. Performance: A tuple is an immutable data type of fixed size. We can easily allot the fixed size memory space to the tuple at the time of creation. We don’t need to see for the memory space again and again as the requisites of the user changes at runtime.
10. Multidimensional: Tuple can also be used as a multidimensional data structure. With a multidimensional tuple, we can easily create a matrix and we can perform different matrix operations on the tuple.
11. Easy to display elements: We can easily display different values stored in the tuple. Even we can display values of tuple without iterating over the tuple.
To display in the simple style, we simply need to write print statement and pass the tuple object to the print() function, which we want to print on the console.
12. Easy to use: The use of tuple data type is a very easy as compared to other data types. It consumes memory dynamically as well as provides various methods to provide an easy way to write the program code.
Concept of Immutable Tuples in Python
Like numbers and strings, tuples in Python are immutable objects. It means that we can change or modify values of tuple elements without creating a new tuple. A new tuple object has to be created if we try to update the existing tuple.
Let’s take an example in which we will try to update a value of an element in the existing tuple and see what happen?
my_tuple = (2, 4, 5, 8, 10) my_tuple = 6 # this operation is not valid for tuple, error will be displayed. print(my_tuple)
Output: my_tuple = 6 # this operation is not valid for tuple, error will be displayed. TypeError: 'tuple' object does not support item assignment
As you can observe in the program code, we are trying to update a value of the third element in the tuple and Python raised an error.
Let’s take an example in which we will try to modify the existing tuple by creating a new tuple object. In this case, no error will generate.
my_tuple1 = (2, 4, 6) my_tuple2 = (8, 10, 12) # Adding two tuples and storing it into a new tuple object. my_tuple3 = my_tuple1 + my_tuple2 # Displaying elements of tuple. print(my_tuple3)
Output: (2, 4, 6, 8, 10, 12)
Multidimensional Tuples in Python
We can make a multidimensional tuple by nesting tuples inside other tuples. A multidimensional tuple can be used to store a matrix or table of information. For example, we can create a 3 * 3 matrix by assigning a tuple of tuples to a variable. Look at the below example code.
matrix = ((2, 4, 6), (8, 10, 12), (14, 16, 18)) print(matrix)
Output: ((2, 4, 6), (8, 10, 12), (14, 16, 18))
Unpacking Tuple Values in Python
We can store or assign a tuple values to variables by using assignment operator. Let us understand it with the help of an example.
n1, n2 = (10, 20) print(n1) print(n2)
Output: 10 20
In the above code, we have allocated 10 to a variable n1 and 20 to a variable n2. This is called unpacking in Python. What happens if we store with more values? Let’s understand it with the below example code.
n1, n2 = (10, 20, 30) print(n1)
Output: n1, n2 = (10, 20, 30) ValueError: too many values to unpack (expected 2)
In the above output, the generated error shows that there are more values to unpack. Let’s understand another example.
n1, n2, n3 = (10, 20) print(n1)
Output: ValueError: not enough values to unpack (expected 3, got 2)
In the above output, the generated error shows that there should be more values in the list to unpack.
Why should we use Tuples in Python?
We should use the tuples in Python due to the following reasons:
- Processing of tuples is much faster than with lists.
- Tuple makes the data safe because of being immutability nature. We cannot modify the content of a tuple.
- We can use tuple for string formatting.
- Tuples functions are faster than with lists.
- Selection of tuple is the best choice if you are dealing out a large amount of data and that data will not change in the future.
- With the help of tuple, we can pass multiple values through one function parameter.
Advantages of Tuples in Python
There are the following advantages of a tuple in Python programming language. They are as:
- Tuples store items in ordered in which we have provided. They preserve our insertion order.
- Tuples allow to add any number of duplicate elements.
- One of the outstanding advantages of using tuples in Python is that we can store elements of different or similar data types on a single tuple.
- Tuples offers security to the data value due to its immutable nature.
- Iterating over elements of a tuple is faster than the list because of its immutability nature.
- Easy to display different values stored in the tuple.
- They provide various useful functions to perform a different set of operations instead of writing long code from scratch.
- Tuple is easy to use as compared to other data types in Python.
Disadvantage of Tuples
Some of the important disadvantages of using tuples in Python are as:
- The advantage of using tuples is that tuples are used for write-protected data, but also disadvantage, as we cannot use it when we will want to add or delete a specific element. Hence, there is limit use of tuple.
- We cannot create a tuple with a single element without using parentheses. In such a case, we need to include a trailing comma which can make the code readability a little bit complex.
- In Python, tuple is not a flexible in nature as it stores elements only once and does not provide any method to update the element values stored in the tuple.
- It provides lesser methods or functions. We require writing our own code to perform certain tasks.
These are some advantages and disadvantages of using tuples in Python programming language that you should keep in mind.
In this tutorial, we have discussed the role of tuples in Python with the help of some important examples. Hope that you will have understood the basic key features tuple and how to create it.
Thanks for reading!!!