Introduction to Tuples in Python
Tuples in Python can be used for defining, declaring and performing operations on a collection of values, and it is represented by the parenthesis(). These tuples have a limited set of pre-defined functions, and the values are of fixed length which cannot be updated or changed once it is created. In Python programming, the tuple functions are immutable in nature, and it does not allow copy functions in the program.
What is a Tuple?
Let’s understand from where we got this named tuple:
This term ‘tuple’ is basically originated for the abstraction of the sequence like 1 is single, 2 is double, 3 is triple, 4 is quadruple, 5 is quintuple, 6 is sextuple, 7 is septuple, 8 is octuple, …and so on…, n‑tuple, …, Here Numerals from Latin names are used as prefixes and tuple is added as a suffix. So now we know how the term tuple came into existence.
How are Tuples Used in Python?
Now let’s discuss how tuples are used in python. Fun fact; a 0‑tuple is pronounced as a null tuple:
As discussed earlier in python, tuples and lists are similar to two basic differences. The first one is tuples are immutable, i.e., once created, we cannot make any changes. You can say this is the basic property, which is the cause of the existence of tuples in python; otherwise, all the other functionality is the same for both tuples and lists. Second one parenthesis (we will discuss in the next section).
What is Immutable in Tuples?
Below are the following points to immutable in tuples:
- One cannot add items to a tuple once it is created. Tuples cannot be appended or extended.
- One cannot remove items from a tuple once it is created. Tuples do not have any remove method.
- One surely can find items in a tuple since finding any item does not make changes in the tuple.
What is the Significance of Immutability?
Below are the points to What is the Significance of Immutability:
- Immutability makes Tuples faster than the lists: For instance, if one defines a set of constant values. It is better to iterate through a tuple instead of a list.
- Immutability of tuples makes one’s code safer: If one wants to “write-protect” the data and not be changed. One should use a tuple in the place of a list. Using tuple implies an assertive statement that the data provided is constant and cannot be modified.
- One can use how tuples are used in python; One cannot use Lists as dictionary keys; the reason is the lists mutable.
Types and Creating Tuples
We cannot categorize tuples instead, we can perform a number of operations with tuples. In this section, we will discuss how to create a tuple, and also, we will discuss a number of operations that can be performed upon tuples:
1. Define Tuples in Two ways
To create a tuple, assign a single variable with multiple values separated by commas in parentheses.
Code:
type1 = (1, 3, 4, 5, 'test')
print (type1)
Output:
To create a tuple, assign a single variable with multiple values separated by commas without parentheses. Please refer introduction for minor difference.
Code:
type2= 1, 4, 6, 'exam', 'rate'
print(type2)
Output:
We can define an empty tuple:
Code:
a = ( )
print(a)
Output:
2. Accessing Items in a Tuple
One can access the elements of a tuple in multiple ways, such as indexing, negative indexing, range, etc.
Code:
access_tuple = ('a', 'b', 1, 3, [5, 'x', 'y', 'z'])
print(access_tuple[0])
print(access_tuple[4][1])
Output:
In case the index value is out of the scope of tuple, it will through the following error.
Code:
print(access_tuple[5])
Output:
We can find the use of negative indexing on tuples.
Code:
access_tuple = ('a', 'b', 1, 3)
print(access_tuple[-1])
Output:
We can find a range of tuples.
Code:
access_tuple = ('a', 'b', 1, 3, 5, 'x', 'y', 'z’)
print(access_tuple[2:5])
Output:
3. Concatenation Operation on Tuples
Concatenation simply means linking things together. We can concatenate tuples together. Here note one thing we can perform different operations on tuples without changing its own definition.
Code:
Tuple1 = (1, 3, 4)
Tuple2 = ('red', 'green', 'blue')
print (Tuple1 + Tuple2)
Output:
4. Nesting Operation on Tuples
Nesting simply means the place or store one or more inside the other.
Code:
Tuple1 = (1, 3, 4)
Tuple2 = ('red', 'green', 'blue')
Tuple3 = (Tuple1, Tuple2)
print (Tuple3)
Output:
5. Slicing Operation on Tuples
As tuples are immutable, we can take slices of one tuple and place them in another tuple.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
Sliced=(Tuple1[2:])
print (Sliced)
Output:
6. Finding length of Tuples
We can find the length of the tuple to see how many values are in there a tuple.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
print(len(Tuple1))
Output:
7. Changing a Tuple
As we know that the tuples are immutable. This means that items defined in a tuple cannot be changed once the tuple has been created.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
Tuple1[1] =4
Output:
Here we have one case, if the item in tuple itself is a mutable data type like a list, its nested items can be changed.
Code:
tuple1 = (1, 2, 3, [4, 5])
tuple1[3][0] = 7
print(tuple1)
Output:
8. Deleting a Tuple
As we have discussed earlier, we cannot change the items in a tuple. which also suggests that we cannot remove items from the tuple.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
del (Tuple1[1])
Output:
But one can delete a tuple by using the keyword del( ) with a tuple.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
del (Tuple1)
print (Tuple1)
Output:
9. Membership Test on Tuples
This can be tested whether an item exists in a tuple or not; the keyword for this is in.
Code:
Tuple1 = (1, 3, 4, 'test', 'red')
print (1 in Tuple1)
print (5 in Tuple1)
Output:
10. Inbuilt functions for Tuples
Python has some built-in functions which can be performed directly on the tuples. For e.g., max(), min(), len(), sum(), sorted() etc.
- max(tuple): It gives the maximum value from the tuple; here, the tuple should not contain string values.
Code:
tuple1 = (1, 2, 3, 6)
print(max(tuple1))
Output:
- min(tuple): It gives the minimum value from the tuple; here the condition is tuple should not contain string values.
Code:
tuple1 = (1, 2, 3, 6)
print(max(tuple1))
Output:
- sum(tuple): The elements in a tuple should be integers only for this operation. The sum will provide a summation of all the elements in the tuple.
Code:
tuple1 = (1, 2, 3, 6)
print(sum(tuple1))
Output:
- sorted(tuple): If the elements are not arranged in order, we can use the sorted inbuilt function.
Code:
tuple2= (1, 4, 3, 2, 1, 7, 6)
print(sorted(tuple2))
Output:
11. Use of Tuples as keys in Dictionaries
We know that tuples are hashable (remain the same thorough out their life span), and the list is not. We should use tuples as the keys to create a composite key and use the same in a dictionary.
Code:
tuplekey = {}
tuplekey[('blue', 'sky')] = 'Good'
tuplekey[('red','blood')] = 'Bad'
print(tuplekey)
Output:
12. Tuple Packing and Unpacking
In packing, we assign the values into a new tuple.
Code:
person = ("Salman", '5 ft', "Actor")
print(person)
In unpacking, we extract the values available in a tuple back into variables. Here one thing must be kept in mind while extracting that the number of unpacking variables must be equal to the number of items in the tuple.
Code:
person = ("Salman", '5 ft', "Actor")
(name, height, profession) = person
print(name)
print(height)
print(profession)
13. Iterate through a Tuple
We can form an iterating loop with tuples.
Code:
my_tuple = ("red", "Orange", "Green", "Blue")
# iterating over tuple elements
for colour in my_tuple:
print(colour)
Output:
14. tuple() Constructor
One can create tuples using a tuple constructor. Here one thing to be noted that to define, we need double brackets.
Code:
Constructortuple = tuple((1, 5, 8, 10))
print (Constructortuple)
Output:
Conclusion- Tuples in Python
In a nutshell, we can say that a tuple is basically a type of data structure that is an ordered collection and cannot be changed once created. A tuple except for immutability and parentheses behaves the same as the list type of data structure in python. This article covers different operations related to tuples, how they are created, and what operations can be performed on the tuples. Tuples are surely faster than the lists and make the code safer.
Recommended Articles
This is a guide to Tuples in Python. Here we discuss various tuples operations, how they are formed and what can be done on the tuples. You can also go through our other related articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses