Tuples are the inbuilt data structure in the Python programming language. In Python, a tuple is similar to a list. It can store the values of different types of elements. In tuples, all values or elements are separated by commas. In Python, tuples are immutable data structures that cannot be modified after they are created.
What is a Python Tuple?
In Python, Tuple uses stored data in a single variable. Tuples are immutable, meaning they cannot be modified after creation. They are defined by enclosing elements within parenthesis ‘()’ separated by commas. Tuple has defined order. A tuple can store any type of data in a single variable. It can store boolean, string and integers.
Syntax of Tuple
myTuple = (1, 2, 3, 'hello', True)
The following program prints the simple tuple.
Program
tuple = ("Books","123", True)
print(tuple)
Output
('Books', '123', True)
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Tuple Characteristics
There are some characteristics of tuples:
Ordered: Tuple data structures maintain the order of elements.
Immutable: Tuple data structures are immutable, It means we cannot change the elements of the tuple data structure.
Allow Duplicates: Tuple data structures can contain duplicate elements.
Python Tuple Types
Python programming language offers two primary types of tuples: named tuples and unnamed tuples.
Named Tuples: Named tuples can be created by class and assigning a name to the new class. Each element within a named tuple corresponds to field records. The following program demonstrates Named tuples.
Unnamed Tuples: Unnamed tuples are easy to create as compared to named tuples. Named tuples elements separated by command. They are storing unstructured data that does not necessitate naming. The following program demonstrates an unnamed tuple example.
Creating Python Tuples
There are various ways to create a tuple in the Python language. The following list is here:
Using round brackets
With one item
Tuple Constructor
Creating a tuple using the round brackets: To create a tuple using the parenthesis () operators.
Program
var = ("Hello", "World", "Computer")
print(var)
Output
('Hello', 'World', 'Computer')
Creating a tuple with one item:
Python 3.11 also provides another way to create a tuple. The following program demonstrates the code.
Tuple Constructor in Python: The tuple constructor in the Python language allows us to create a tuple. The following program demonstrates the tuple constructor.
The following operations are performed in tuples in Python language.
Concatenation
Nesting
Repetition
Slicing
Deleting
Finding the Length
Multiple Data Type with tuples
Conversion of the list to tuples
Tuples in a Loop
Tuple Membership Test
In Python, we can also check whether the substring is in string or using the in operator. If the string is available in Python, it will return true; otherwise, it will return false. The following program demonstrates the tuple membership test.
Program
tuple_ = ("Hello", "Computer", "Wordholic", "Scientist", "Torture", "Multiple Disorder")
# In operator
print('Hello' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Output
True
False
True
True
How to Access Tuples?
In Python, tuples are accessed similarly to lists, but they are immutable; this means we cannot change their elements once they are created. Let’s see how we can access the Tuples.
Accessing by Index: We can access elements in a tuple using the square brackets.’[]’ and pass the index. Python uses zero-based indexing. It means the first element is 0.
Python tuple is unchangeable. This means we cannot change the original tuple. If you attempt to directly modify a tuple, you’ll encounter an error. However, you can achieve a similar effect by creating a new tuple or converting a tuple into a list and then converting the list once again into a tuple.
Concatenation: We can modify a tuple using the concatenation of two tuples to create a new tuple.
In Python, unpacking is a convenient way to assign value to individual variables. It can be done by a single line of code. The following program demonstrates “how we can unpack the tuple”.
Program
# Define a tuple
myTuple = (1, 2, 3)
# Unpack the tuple into individual variables
a, b, c = myTuple
# Print the variables
print(a)
print(b)
print(c)
Output
1
2
3
Using Asterisk: If the number of variables is less than the number of values, we can use the * to the variable name. It assigns the rest of the values in a single variable.
The following program demonstrates the using the asterisk:
We can also use loops with tuples in the Python programming language. It iterates over the elements of the tuple. There are many ways to do this using for-loop.
Using for loop: The following program demonstrates the for loop with tuples.
Program
my_tuple = (1, 2, 3, 4, 5)
# Iterate over the tuple using a for-loop
for item in my_tuple:
print(item)
Output
1
2
3
4
5
Using a while loop: The following program demonstrates the while loop for tuples.
Program
myTuple = (1, 2, 3, 4, 5)
index = 0
# Using a while loop to iterate over the tuple
while index < len(my_tuple):
print(my_tuple[index])
index += 1
Output
1
2
3
4
5
How to Join Two Tuples?
We can also join two tuples using the ‘+’ operators to concatenate them. It will create a new tuple that contains both elements from both tuples.
The following program demonstrates the joining of two tuples:
Program
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Joining two tuples using the + operator
joined_tuple = tuple1 + tuple2
print(joined_tuple)
Output
(1, 2, 3, 4, 5, 6)
We can also use the tuple constructor to join two tuples. The following program uses the tuple constructor.
Program
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Joining two tuples using the tuple() constructor
joined_tuple = tuple(tuple1 + tuple2)
print(joined_tuple)
Output
(1, 2, 3, 4, 5, 6)
Deleting a Tuple in Python
In this section, we will delete the tuple using the del keyword. The output will form an error because you have already deleted the tuple. It will give the NameError.
Remember: We cannot delete the individual element from the tuple. But we can delete the whole tuple using the del keyword.
Program
# Code for deleting a tuple
tuple3 = ( 0, 1)
print(tuple3)
del tuple3
print(tuple3)
Output
(0, 1)
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
NameError: name 'tuple3' is not defined
Finding the Length of a Python Tuple
We can find the length of a tuple using the Python len() function and pass the tuple as the parameter.
Program
# Code for printing the length of a tuple
tuple2 = ('python', 'computer','wrong', 'song')
print(len(tuple2))
Output
4
Multiple Data Types With Tuplecture
In Python, Tuples are heterogeneous data structures. This means they support elements with multiple data types. The following program demonstrates the use of multiple tuples in a single tuple.
Program
# tuple with different data types
tuple_types = ("Workaholic problem",True,23)
print(tuple_types)
Output
('Workaholic problem', True, 23)
Converting a List to a Tuple
We can convert the list into a tuple using the tuple constructor. The following program demonstrates the list to a tuple.
Program
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('Harry Potter’))
We can also create a tuple of multiple elements from a single element in that tuple. The following program demonstrates the repetition of a Python tuple.
In tuples, iterations are comparatively faster than list
Inserting and deleting items is easier with a list
Accessing the elements is best accomplished with tuple data type
List consumers with more memory in the computer system.
Tuples consume less memory than list
In the list, unexpected changes occur more as compared to a tuple Because lists are mutable
In a tuple, changes and more errors don’ n’t usually occur because of immutability
Built-in Methods
Built-in-Method
Description
index()
Find in the tuple and return the index of the given value if the value is available
count()
This method returns the frequency of occurrence of species value.
Conclusion
In this article, we learned about tuples in Python and saw that they are immutable data structures. After defining a tuple, we cannot change its original state. A tuple stores heterogeneous elements. It can store different data types, including number, strings list, and other tuples. We also learned various approaches to access the tuple and modify the existing tuple. Overall, tuples provide a lightweight and efficient way to store and work immutable sequences of data in Python. If you want to learn more about the Python language, consider pursuing the Accelerator Program in Business Analytics and Data Science.
FAQs
What is a tuple in Python?
A tuple is an ordered and immutable collection of elements. Tuple enclosed within parenthesis ‘()’. It can contain elements of different data types, separated by commas.
How do you create a tuple in Python?
Tuples can be created by enclosing within parentheses ‘()’, separated by command, for example ‘myTuple=(1,2,3)’.
How do you iterate over a tuple in Python?
We can iterate over a tuple using a ‘for’ loop and ‘while’ loop or other iterable methods like ‘enumerate()
Can you concatenate two tuples in Python?
Yes, we can concatenate two tuples using the ‘+’ operator or the ‘tuple()’ constructor.
How do you access elements in a tuple?
Indexing can access a tuple. In Python, indexing starts at 0. ‘Mytuple[0]’ will access the first element.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.