A tuple in Python is an immutable sequence data structure which means that you cannot modify the value of the existing elements of a tuple once created. Tuples can be used to store data of different types and can be of any length. Python tuples come in handy when you have to return multiple values from functions, or if you need to group multiple values together into a single entity, such as an array of objects. I highly recommend you get the “Python Crash Course Book” to learn Python.
How to Create a Tuple?
There are different methods to create a tuple in Python. Three methods are given:
Method 1:
In this method, tuple is created using parentheses.
# Tuple a = (5, 10, 15, 20) # Display the tuple print(a) # Display Type print(type(a))
Output:
(5, 10, 15, 20) <class 'tuple'>
Method 2:
In this method, tuple is created using tuple keyword and double parentheses.
# Tuple a = tuple((5, 10, 15, 20)) # Display the tuple print(a) # Display Type print(type(a))
Output:
(5, 10, 15, 20) <class 'tuple'>
Method 3
You can also create tuple without parentheses.
# Tuple a = "AiHints", 5, 10.4 # Display the Tuple print(a) # Display the type print(type(a))
Output:
('AiHints', 5, 10.4) <class 'tuple'>
Tuple with different Data Types
You can use different data types in tuple.
a = (5, 10, 15, 20) b = ('ML', 'DL', 'AI', 'DS') c = (5.2, 3.7, 12.45, 2.9) d = ('AiHints', 20, 3.4, True, False) # Display tuple print(a) print(b) print(c) print(d) # Display Type print(type(a)) print(type(b)) print(type(c)) print(type(d))
Output:
(5, 10, 15, 20) ('ML', 'DL', 'AI', 'DS') (5.2, 3.7, 12.45, 2.9) ('AiHints', 20, 3.4, True, False) <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'>
Nested Tuple
You can aslo create a tuple in which list and tuple may be its elements.
# Tuple a = ([5, 10, 15, 20], "AiHints", (4.3, 2.5, 3)) # Display the Tuple print(a) # Display the Type print(type(a))
Output:
([5, 10, 15, 20], 'AiHints', (4.3, 2.5, 3)) <class 'tuple'>
Empty Tuple
For empty tuple, just use the parentheses without any item.
# Tuple a = () # Display the Tuple print(a) # Display the Type print(type(a))
Output:
() <class 'tuple'>
Length of Tuple
You can easily find the total number of elements of the tuple using built-in function len().
# Tuple a = (5, 10, 15, 20) # Length of Tuple len(a)
Output:
4
Tuple with one element
a = (5) b = (5,) print(type(a)) print(type(b))
Output:
<class 'int'> <class 'tuple'>