Tuples in Python with Examples
In this article, I am going to discuss Tuples in Python with examples. Please read our previous article where we discussed Lists in Python with examples. As part of this article, we are going to discuss the following pointers which are related to Tuples in Python.
- What is tuple data structure?
- Different ways to create a tuple.
- Accessing elements of tuple
- Tuple vs immutability
- Important functions and methods of Tuple:
- Tuple packing
- Tuple unpacking:
- Tuple comprehensions
- Differences between List and Tuple
- Multiple Programs to understand above concepts
What are Tuples in Python?
A tuple refers to a collection of objects in python which are ordered and can’t be changed. The python objects here may be strings, lists, tuples, integers etc.
Characteristics and Features of Tuples in Python:
- Insertion order is preserved: The order in which elements are added to the tuple is the order in which the output will be displayed.
- Immutable: Once if we create a tuple object, then we cannot modify the content of the tuple object. This is the only feature which differentiates tuples from the lists.
- Tuple can store duplicates.
- Tuple can store the same type of objects and different types of objects as well.
- Index plays the main role in tuple.
- Tuple supports both positive and negative indexes. Positive index means forward direction (from left to right). Negative index means backward direction (from right to left).
- We can create a tuple by using parenthesis () symbol. Parenthesis is optional but it’s recommended to use.
- Inside the tuple every object should be separated by comma as a separator.
When should we go for tuple data structure in python?
If we are going to define a data which is not going to change over the period, then we should go for tuple data structure. For example, weekdays, calendar months, years etc. Let us see an example for better understanding.
Example: Tuple having same type of objects (demo1.py)
employee_ids = (1, 2, 3, 4, 5) print("same type of objects:",employee_ids) print(type(employee_ids))
Note: parenthesis are optional, when creating tuples.
Example: Parenthesis is optional for tuple (Demo2.py)
employee_ids = 1, 2, 3, 4, 5 print("same type of objects:",employee_ids) print(type(employee_ids))
Example: Different elements in tuple (demo3.py)
employee_details = (1, "RGV", 1000.123) print("different type of objects:", employee_details)
Single Value tuple
If a tuple has only one object, then that object should end with a comma separator otherwise python, internally, will not consider it as a tuple.
Example: Single Value Tuple (demo4.py)
name =("Sushanth") print(name) print(type(name))
Example: Single Tuple value (demo5.py)
a = (11) print(a) print(type(a))
Example: Single Tuple (demo6.py)
name =("Sushanth",) print(name) print(type(name))
Different Ways to Create Tuples in Python:
- Empty Tuple
- Single value tuple
- Tuple with group of values
- By using tuple() function
Empty Tuple in Python:
We can create an empty tuple by using empty parenthesis.
Example: Empty Tuple (demo7.py)
emp_id = () print(emp_id) print(type(emp_id))
Single Value Tuple
We can create a single value tuple in two ways:
- Using parenthesis – Comma is mandatory.
- Without using parenthesis – Comma is mandatory
Example:Single Value Tuple (demo8.py)
emp_id = (11,) std_id = 120, print(emp_id) print(std_id)
Tuple with group of values
Tuple can contain group of objects; those objects can be of the same type or different types. While creating tuple with group of values parentheses are optional.
Example: Tuple with group of Values (demo9.py)
emp_id = (11, 12, 13) std_id = 120, 130, 140 print(emp_id) print(std_id)
By using tuple() function
We can create a tuple by using tuple() function.
Example: Using Tuple Function (demo10.py)
l = [11, 22, 33] t=tuple(l) print(t)
Example: Using Tuple Function (demo11.py)
t=tuple(range(1, 10, 2)) print(t)
Different Ways to Access Tuples in Python:
We can access tuple elements in three ways,
- Slicing operator
These are the methods which we discussed in the lists chapter. So, let’s move on with examples.
Accessing Tuples using Indexing in Python:
Index refers to the position where the element is stored. This is same as what we discussed in case of strings and lists.
Example: Indexing (demo12.py)
t=(10,20,30,40,50,60) print(t) # 10 #Positive indexing print(t[-1]) # 60 #Negative indexing #print(t) # IndexError: tuple index out of range
Accessing Tuples using Slicing operator in Python:
Example: Slicing Operator(demo13.py)
t=(10,20,30,40,50,60) print(t[2:5]) print(t[2:100]) print(t[::2])
Accessing Tuples using Looping in Python:
t=(10,20,30,40,50,60) for i in t: print(i)
Tuple having immutable nature. If we create a tuple then we cannot modify the elements of the existing tuple. The operations/functions/methods on tuples, which we are going to see now, will create and return new objects (lists, strings, tuples) depending on the operation, but not change the existing tuple because of its immutability.
Example: Immutability (demo15.py)
We can apply plus (+) and Multiplication (*) operators on tuple.
- + operator works as concatenation.
- * operator works as multiplication.
Concatenation operator (+):
This operator concatenates two tuples and returns a single new tuple object.
Example: Concatenation (demo16.py)
t1=(10,20,30) t2=(40,50,60) t3=t1+t2 print(t3)
Multiplication operator (*):
Multiplication operator works as repetition operator, and returns a single, new, repeated tuple object.
Example: Multiplication (demo17.py)
t1=(10,20,30) t2=t1*3 print(t2)
IMPORTANT METHODS and FUNCTIONS of Tuples in Python:
- len() function
- count() method
- index() method
- sorted() function
- min() and max() functions
len() function in Tuples:
It returns number of elements present in the tuple.
Example: len() function (demo18.py)
count() method in Tuples:
It returns number of occurrences of given element in the tuple.
Example: count() method (demo19.py)
index() method in Tuples:
It returns the index of first occurrence of the given element. If the specified element is not available, then we will get ValueError.
Example: index() method (demo20.py)
t=(10,20,10,10,20) print(t.index(10)) # print(t.index(30))# # ValueError
Example: index() method in Tuples (demo21.py)
t=(10,20,10,10,20) #print(t.index(10)) print(t.index(30))# # ValueError
sorted() function in Tuples:
This function can sort the elements which is default natural sorting order. This returns a sorted list of elements.
Example: sorted() method in Tuples (demo22.py)
t=(40,10,30,20) t1=sorted(t) print(t) print(t1)
We can sort according to reverse of default natural sorting order as below
Example: sorted() method in Tuples (demo23.py)
t=(40,10,30,20) t1=sorted(t,reverse=True) print(t1)
min() and max() functions in Tuples:
These functions return min and max values according to default natural sorting order.
Example: min() and max() method in Tuples (demo24.py)
t=(40,10,30,20) print(min(t)) # 10 print(max(t)) # 40
We can create a tuple by packing a group of variables.
Example: tuple packing (demo25.py)
a=10 b=20 c=30 d=40 t=a, b, c, d print(t)
Tuple unpacking is the reverse process of tuple packing, we can unpack a tuple and assign its values to different variables
Example: tuple unpacking (demo26.py)
t=(10, 20, 30, 40) a, b, c, d = t print("a=",a , "b=" , b," c=", c ,"d=",d)
Note: At the time of tuple unpacking the number of variables and number of Values should be the same, otherwise we will get ValueError.
Tuple comprehension is not supported by Python. For example, let’s consider,
t= (x**2 for x in range (1,6))
This expression after execution will return a generator object in ‘t’ rather than a tuple object. We need to run it using a loop
Example: Tuple comprehension (demo27.py)
t= ( x**2 for x in range(1,6)) print(type(t)) for x in t: print(x)
DIFFERENCES BETWEEN LISTS and TUPLES in PYTHON:
List and Tuple are exactly the same except for a small difference: List objects are mutable Whereas Tuple objects are immutable. In both cases insertion, the order is preserved, duplicate objects are allowed, heterogeneous objects are allowed, index and slicing are supported.
In the next article, I am going to discuss Sets in Python. Here, in this article, I try to explain Tuples in Python with Examples. I hope you enjoy this Tuples in Python with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.