Python Tuple
A tuple is a collection similar to a Python list. The primary difference is that we cannot modify a tuple once it is created.
Create a Python Tuple
We create a tuple by placing items inside parentheses ().
For example,
numbers = (1, 2, -5)
print(numbers)
# Output: (1, 2, -5)
Create a Tuple Using tuple() Constructor
We can also create a tuple using a tuple() constructor.
For example,
tuple_constructor = tuple(('Jack', 'Maria', 'David'))
print(tuple_constructor)
# Output: ('Jack', 'Maria', 'David')
Understanding Tuple Methods
Tuple methods are built-in functions in Python that can be used to perform operations on tuples. These methods provide a
convenient way to manipulate and analyze tuple data. Let’s explore some of the commonly used tuple methods.
Tuple Creation and Access
Before diving into tuple methods, let’s first understand how to create tuples in Python and how to access their elements.
Step 1: Creating Tuples in Python
Tuples can be created in Python using parentheses or the tuple() function. Here’s an example:
# Creating a tuple using parentheses
my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Creating a tuple using the tuple() function
my_tuple = tuple([1, 2, 3, 'a', 'b', 'c'])Copy Code
Step 2: Accessing Elements in a Tuple
Elements in a tuple can be accessed using indexing or slicing.
Indexing
Indexing allows us to access individual elements in a tuple by their position. The index starts from 0 for the first element and
increments by 1 for each subsequent element. Here’s an example:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Accessing the first element
print(my_tuple[0]) # Output: 1
# Accessing the fourth element
print(my_tuple[3]) # Output: 'a'Copy Code
Slicing
Slicing allows us to access a range of elements in a tuple. It is done by specifying the start and end indices, separated by a
colon. Here’s an example:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Accessing elements from index 1 to 3
print(my_tuple[1:4]) # Output: (2, 3, 'a')
Python provides several built-in methods to perform operations on tuples. Here are some of the most commonly used tuple
methods:
Method/Function Description
count() Returns the number of occurrences of a specified element in a tuple.
index() Returns the index of the first occurrence of a specified element in a tuple.
len() Returns the number of elements in a tuple.
sorted() Returns a new tuple with the elements sorted in ascending order.
min() Returns the smallest element in a tuple.
max() Returns the largest element in a tuple.
tuple() Converts an iterable object into a tuple.
Let’s explore each of these methods in detail with examples.
count() Method
The count() method counts the number of occurrences of a specified element in a tuple functions in python. It takes a single
argument, which is the element to be counted. Here’s an example:
my_tuple = (1, 2, 3, 2, 4, 2)
# Counting the number of occurrences of 2
count = my_tuple.count(2)
print(count) # Output: 3Copy Code
index() Method
The index() method finds the index of the first occurrence of a specified element in a tuple. It takes a single argument, which is
the element to be searched. Here’s an example:
my_tuple = (1, 2, 3, 2, 4, 2)
# Finding the index of the first occurrence of 2
index = my_tuple.index(2)
print(index) # Output: 1Copy Code
len() Method
The len() method is used to find the number of elements in a tuple. It takes no arguments and returns an integer value
representing the length of the tuple. Here’s an example:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Finding the length of the tuple
length = len(my_tuple)
print(length) # Output: 6Copy Code
sorted() Method
The sorted() method sorts the elements of a tuple in ascending order. It takes no arguments and returns a new tuple with the
sorted elements. Here’s an example:
my_tuple = (3, 1, 4, 2)
# Sorting the elements of the tuple
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: (1, 2, 3, 4)Copy Code
min() and max() Methods
The min() and max() methods find the smallest and largest elements in a tuple, respectively. They take no arguments and
return the smallest and largest elements, respectively. Here’s an example:
my_tuple = (3, 1, 4, 2)
# Finding the smallest element in the tuple
smallest = min(my_tuple)
print(smallest) # Output: 1
# Finding the largest element in the tuple
largest = max(my_tuple)
print(largest) # Output: 4
Python Tuple Operations
In addition to tuple methods, various operations can be performed on tuples. Let’s explore some of these operations.
Concatenating Tuples
Tuples can be concatenated using the ‘+’ operator. This operation creates a new tuple by combining the elements of two or
more tuples. Here’s an example:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
# Concatenating two tuples
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')Copy Code
Replicating Tuples
Tuples can be replicated using the ‘*’ operator. This operation creates a new tuple by repeating the elements of a tuple a
specified number of times. Here’s an example:
my_tuple = (1, 2, 3)
# Replicating a tuple three times
replicated_tuple = my_tuple * 3
print(replicated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)Copy Code
Updating Tuples
Since tuple methods in python are immutable, you cannot update their elements directly. However, you can update tuples
indirectly by converting them into lists, modifying the list, and then converting it back into a tuple. Here’s an example:
my_tuple = (1, 2, 3)
# Converting the tuple into a list
my_list = list(my_tuple)
# Updating the list
my_list[1] = 4
# Converting the list back into a tuple
updated_tuple = tuple(my_list)
print(updated_tuple) # Output: (1, 4, 3)Copy Code
Deleting Tuples
Tuples, being immutable, cannot be deleted directly. However, we can use the ‘del’ keyword to delete the entire tuple. Here’s
an example:
my_tuple = (1, 2, 3)
# Deleting the tuple
del my_tuple
# Trying to access the tuple after deletion will raise an error
print(my_tuple) # Output: NameError: name 'my_tuple' is not defined
SETS
Python Sets
A set is a collection of unique data, meaning that elements within a set cannot be duplicated.
For instance, if we need to store information about student IDs, a set is suitable since student IDs cannot have duplicates.
Python Set
Elements
Create a Set in Python
In Python, we create sets by placing all the elements inside curly braces {}, separated by commas.
A set can have any number of items and they may be of different types (integer, float, tuple, string, etc.). But a set cannot have
mutable elements like lists, sets or dictionaries as its elements.
Let's see an example,
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
Run Code
Output
Student ID: {112, 114, 115, 116, 118}
Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}
Create an Empty Set in Python
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python.
To make a set without any elements, we use the set() function without any argument. For example,
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }
# check data type of empty_set
print('Data type of empty_set:', type(empty_set))
# check data type of dictionary_set
print('Data type of empty_dictionary:', type(empty_dictionary))
Run Code
Output
Data type of empty_set: <class 'set'>
Data type of empty_dictionary: <class 'dict'>
Here,
empty_set - an empty set created using set()
empty_dictionary - an empty dictionary created using {}
Finally, we have used the type() function to know which class empty_set and empty_dictionary belong to.
Built-in Functions with Set
Here are some of the popular built-in functions that allow us to perform different operations on a set.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.
Python Set Operations
Python Set provides different built-in methods to perform mathematical set operations like union, intersection, subtraction,
and symmetric difference.
Union of Two Sets
The union of two sets A and B includes all the elements of sets A and B.
Set Union in Python
We use the | operator or the union() method to perform the set union operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
# perform union operation using |
print('Union using |:', A | B)
# perform union operation using union()
print('Union using union():', [Link](B))
Run Code
Output
Union using |: {0, 1, 2, 3, 4, 5}
Union using union(): {0, 1, 2, 3, 4, 5}
Note: A|B and union() is equivalent to A ⋃ B set operation.
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
Set Intersection in Python
In Python, we use the & operator or the intersection() method to perform the set intersection operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
# perform intersection operation using &
print('Intersection using &:', A & B)
# perform intersection operation using intersection()
print('Intersection using intersection():', [Link](B))
Run Code
Output
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}
Note: A&B and intersection() is equivalent to A ⋂ B set operation.
Difference between Two Sets
The difference between two sets A and B include elements of set A that are not present on set B.
Set Difference in Python
We use the - operator or the difference() method to perform the difference between two sets. For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('Difference using &:', A - B)
# perform difference operation using difference()
print('Difference using difference():', [Link](B))
Run Code
Output
Difference using &: {3, 5}
Difference using difference(): {3, 5}
Note: A - B and [Link](B) is equivalent to A - B set operation.
Set Symmetric Difference
The symmetric difference between two sets A and B includes all elements of A and B without the common elements.
Set Symmetric Difference in Python
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric differences between two sets.
For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('using ^:', A ^ B)
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Check if two sets are equal
We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
# perform difference operation using &
if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')
Run Code
Output
Set A and Set B are equal
In the above example, A and B have the same elements, so the condition
if A == B
evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is executed.
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available
with the set objects:
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
Removes an element from the set if it is a member. (Do nothing if the element
discard()
is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
Removes and returns an arbitrary set element. Raises KeyError if the set is
pop()
empty
Removes an element from the set. If the element is not a member, raises a
remove()
KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others