Python Tuples
A tuple is an intrinsic data structure in Python used for the storage of a collection of items. In many ways, a tuple resembles a Python list with respect to indexing, the ability to contain nested objects, and the allowance for duplicate entries. Nonetheless, the key distinction between the two is that tuples in Python are immutable, whereas lists are mutable.
Let's explore a straightforward illustration of how to create a tuple in Python.
Example
# creating a tuple
T = (20, 'ExampleTech', 35.75, [20, 40, 60])
print(T)
Output:
(20, 'ExampleTech', 35.75, [20, 40, 60])
Explanation:
In the above example, we have created a simple tuple consisting of multiple elements of different data types. Each element in this tuple is indexed, meaning it can be accessed using its position in the list, as shown below:
- T[0] = 20 (Integer)
- T[1] = 'Example' (String)
- T[2] = 35.75 (Float)
- T[3] = [20, 40, 60] (Nested List)
Characteristics of Python Tuples
In Python, a tuple is a type of data structure that is characterized by the following properties:
- Ordered: The elements within a tuple are arranged in a specific sequence that remains constant.
- Immutable: Once a tuple is created, its elements cannot be modified or altered.
Let’s examine the subsequent example that demonstrates the immutability of Tuples.
Example
# creating a tuple
my_tpl = (25, 16.25, 'Example', [20, 40, 60], 3e8)
print(my_tpl)
# trying to changing the element of the tuple
# my_tpl[1] = 'welcome' # raise TypeError
Output:
(25, 16.25, 'Example', [20, 40, 60], 300000000.0)
Creating a Tuple
All entities, commonly referred to as "elements," should be divided by a comma and enclosed within parentheses . While the use of parentheses is not mandatory, it is advisable to include them.
A tuple can hold an arbitrary number of items, encompassing a range of data types such as dictionaries, strings, floats, lists, and more.
Let us examine the subsequent illustration that showcases the incorporation of various data types within a tuple:
Example
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tpl = ()
print("Empty tuple: ", empty_tpl)
# Creating a tuple having integers
int_tpl = (13, 56, 27, 18, 11, 23)
print("Tuple with integers: ", int_tpl)
# Creating a tuple having objects of different data types
mix_tpl = (6, "ExampleTech", 17.43)
print("Tuple with different data types: ", mix_tpl)
# Creating a nested tuple
nstd_tpl = ("ExampleTech", {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))
print("A nested tuple: ", nstd_tpl)
Output:
Empty tuple: ()
Tuple with integers: (13, 56, 27, 18, 11, 23)
Tuple with different data types: (6, 'ExampleTech', 17.43)
A nested tuple: ('ExampleTech', {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))
Explanation:
In the code snippet provided above, four distinct tuples have been created, each containing various types of elements. The initial tuple is an empty one, established by using parentheses without including any elements within them. Following this, we have defined a tuple that contains integers, which is made up of six integer values enclosed within parentheses and separated by commas. The third tuple consists of three elements of varying data types: an integer, a string, and a float. Finally, we have constructed a tuple that acts as a separate object, which includes another tuple as one of its elements.
Accessing Tuple Elements
In Python, we can retrieve any element from a tuple by utilizing its indices. The items or elements contained within a tuple can be accessed by specifying the index number, enclosed in square brackets ''.
Let us examine the subsequent example that demonstrates how to retrieve an element from a tuple by utilizing indexing:
Example
# Python program to show how to access tuple elements
# Creating a tuple having six elements
sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")
# accessing the elements of a tuple using indexing
print("sampleTuple[0] =", sampleTuple[0])
print("sampleTuple[1] =", sampleTuple[1])
print("sampleTuple[-1] =", sampleTuple[-1]) # negative indexing
print("sampleTuple[-2] =", sampleTuple[-2])
Output:
sampleTuple[0] = Apple
sampleTuple[1] = Mango
sampleTuple[-1] = Berries
sampleTuple[-2] = Guava
Explanation:
In the preceding illustration, we have formed a tuple that contains a total of six elements. Following that, we employed indexing techniques to retrieve the various elements from the tuple.
Slicing in Tuple
Slicing a tuple involves breaking down a tuple into smaller tuples utilizing indexing. To perform a slice on a tuple, it is essential to indicate both the starting and ending index values. This process will yield a new tuple containing the elements within the defined range.
A tuple can be sliced by utilizing the colon ':' operator, which distinguishes the beginning and ending indices, as demonstrated in the example below:
Syntax:
It has the following syntax:
tuple[start:end]
Python Tuple Slicing Example
Let's examine a straightforward illustration that demonstrates how to slice a tuple in Python.
Example
# Python program to show how slicing works in Python tuples
# Creating a tuple
sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 5: ", sampleTuple[1:5])
# Using negative indexing in slicing
print("Elements between indices 0 and -3: ", sampleTuple[:-3])
# Printing the entire tuple by using the default start and end values
print("Entire tuple: ", sampleTuple[:])
Output:
Elements between indices 1 and 5: ('Mango', 'Banana', 'Orange', 'Guava')
Elements between indices 0 and -3: ('Apple', 'Mango', 'Banana')
Entire tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
Explanation:
In this illustration, we have created a tuple that contains six items: Apple, Mango, Banana, Orange, Guava, and Berries. We utilized the slicing technique to display the elements from index 1 to 5. Following that, we extracted and printed the elements from index 0 to -3 by employing negative indexing in our slicing approach. Finally, we displayed the complete tuple by using the colon ':' operator without providing any specific start or end index values.
Deleting a Tuple
In contrast to lists, tuples are characterized as immutable data types, indicating that once a tuple is formed, its elements cannot be modified. Consequently, it is also not feasible to eliminate individual items from a tuple. Nevertheless, one can remove the entire tuple by utilizing the 'del' keyword, as demonstrated in the following example.
Syntax:
It has the following syntax:
del tuple_name
Python Example to Delete a Tuple
Let's examine the subsequent code snippet that demonstrates how to remove a tuple using the 'del' keyword. Below is a straightforward example that illustrates the process of deleting a tuple in Python.
Example
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")
# printing the entire tuple for reference
print("Given Tuple:", sampleTuple)
# Deleting a particular element of the tuple using the del keyword
try:
del sampleTuple[3]
print(sampleTuple)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program using the del keyword
del sampleTuple
# Trying accessing the tuple after deleting it
try:
print(sampleTuple)
except Exception as e:
print(e)
Output:
Given Tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
'tuple' object doesn't support item deletion
name 'sampleTuple' is not defined
Explanation:
In this scenario, we have created a tuple that includes six components: Apple, Mango, Banana, Orange, Guava, and Berries. Subsequently, we displayed the complete tuple for our reference. Following this, we employed try and except blocks to remove a specific item from the tuple utilizing the del keyword. Consequently, an exception was triggered indicating that a 'tuple' object does not allow item deletion. We then proceeded to use the del keyword to eliminate the entire tuple and attempted to print it. As a result, we encountered yet another exception stating that the name 'sampleTuple' is not defined.
Changing the Elements in Tuple
After a tuple is created, its elements cannot be altered because of its immutable characteristics. Nevertheless, there exists a method for modifying the elements of a tuple. This can be accomplished by converting the tuple into a list, making the necessary modifications to the list, and then converting the list back into a tuple.
Python Example to Change the Element in Tuple
Let's examine a straightforward example that demonstrates how to modify elements within a Tuple in Python.
Example
# Python program to demonstrate the approach of changing the element in the tuple
# creating a tuple
fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")
# printing the tuple before update
print("Before Changing the Element in Tuple...")
print("Tuple =", fruits_tuple)
# converting the tuple into the list
fruits_list = list(fruits_tuple)
# changing the element of the list
fruits_list[2] = "grapes"
print("Converting", fruits_tuple[2], "=>", fruits_list[2])
# converting the list back into the tuple
fruits_tuple = tuple(fruits_list)
# printing the tuple after update
print("After Changing the Element in Tuple...")
print("Tuple =", fruits_tuple)
Output:
Before Changing the Element in Tuple...
Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Converting banana => grapes
After Changing the Element in Tuple...
Tuple = ('mango', 'orange', 'grapes', 'apple', 'papaya')
Explanation:
In this demonstration, we have constructed a tuple containing five items: mango, orange, banana, apple, and papaya. Following that, we displayed the tuple for clarity. Subsequently, we utilized the list function to transform the tuple into a list. We then modified the item located at index 2 of the list to 'grapes' and employed the tuple function to revert the updated list back into a tuple. Finally, we printed the resulting tuple. Consequently, we can see that the tuple has been altered, with the item at index 2 changing from 'banana' to 'grapes'.
Adding Elements to a Tuple
Given that a Tuple is an immutable data structure, it lacks the built-in append method typically used for adding elements. Nevertheless, there are several methods available that allow us to incorporate an element into a tuple.
Converting the Tuple into a List
To introduce a new element into a tuple, we can adopt a method akin to the one we employed for modifying an element within a tuple. This method encompasses the steps outlined below:
Step 1: Convert the Tuple into a List.
Step 2: Incorporate the necessary element into the list by utilizing the append method.
Step 3: Convert the List back into the Tuple.
Let's examine the subsequent code snippet, which illustrates this concept.
Example
# Python program to demonstrate an approach of adding the element in the tuple by converting it into a list
# creating a tuple
fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")
# printing the tuple before update
print("Before Adding a New Element in Tuple...")
print("Original Tuple =", fruits_tuple)
# converting the tuple into the list
fruits_list = list(fruits_tuple)
# changing the element of the list
fruits_list.append("blueberry")
print("Adding New Element -> 'blueberry'")
# converting the list back into the tuple
fruits_tuple = tuple(fruits_list)
# printing the tuple after update
print("After Adding a New Element in Tuple...")
print("Updated Tuple =", fruits_tuple)
Output:
Before Adding a New Element in Tuple...
Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Adding New Element -> 'blueberry'
After Adding a New Element in Tuple...
Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'blueberry')
Explanation:
In the code snippet provided above, we have established a tuple that contains five items: mango, orange, banana, apple, and papaya. Subsequently, we printed the tuple for our reference. Following this, we transformed the tuple into a list by utilizing the list function. We then incorporated a new item, 'blueberry', into the list using the append function. After that, we applied the tuple function to convert the modified list back into a tuple. Finally, we printed the resulting tuple. Consequently, we can see that the tuple has been modified and the item 'blueberry' has been successfully added to the original tuple.
Adding a Tuple to a Tuple
In Python, it is possible to concatenate multiple tuples together. Consequently, if we wish to add a new item to an existing tuple, we can adhere to the steps outlined below:
Step 1: Instantiate a new Tuple containing the element(s) that we wish to include.
Step 2: Incorporating the new tuple into the current tuple.
Let us examine the subsequent example, which demonstrates this concept.
Example
# Python program to demonstrate an approach of adding the element in the tuple by adding a new tuple to the existing one
# creating a tuple
fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")
# printing the tuple before update
print("Before Adding a New Element in Tuple...")
print("Original Tuple =", fruits_tuple)
# creating a new tuple consisting new element(s)
temp_tuple = ("pineapple", )
# adding the new tuple to the existing tuple
# fruits_tuple = fruits_tuple + temp_tuple
fruits_tuple += temp_tuple
# printing the tuple after update
print("Adding New Element -> 'pineapple'")
print("After Adding a New Element in Tuple...")
print("Updated Tuple =", fruits_tuple)
Output:
Before Adding a New Element in Tuple...
Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Adding New Element -> 'pineapple'
After Adding a New Element in Tuple...
Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'pineapple')
Explanation:
In the code segment presented above, a tuple has been formed containing five items: mango, orange, banana, apple, and papaya. Subsequently, this tuple is displayed for reference. Following this, a new tuple is created that includes an additional item, 'blueberry'. This new tuple is then combined with the original tuple using the '+' operator. Finally, the updated tuple is printed. Consequently, we can see that the tuple has been modified, and the item 'pineapple' has been incorporated into the original tuple accordingly.
Unpacking Tuples
When we create a tuple, we typically assign various objects to it. This action is referred to as 'packing' a tuple. In addition, Python provides a convenient way to retrieve those objects and allocate them to individual variables. This method of retrieving objects from a tuple and distributing them to separate variables is called 'unpacking' a tuple.
Python Example for Unpacking Tuples
Let us examine the subsequent example that demonstrates the method of unpacking a tuple in Python.
Example
# Python program to demonstrate an approach of unpacking a tuple
# creating a tuple (Packing a Tuple)
fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")
# printing the given tuple for reference
print("Given Tuple :", fruits_tuple)
# unpacking a tuple
(varOne, varTwo, varThree, varFour, varFive) = fruits_tuple
# printing the results
print("First Variable :", varOne)
print("Second Variable :", varTwo)
print("Third Variable :", varThree)
print("Fourth Variable :", varFour)
print("Fifth Variable :", varFive)
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
First Variable : mango
Second Variable : orange
Third Variable : banana
Fourth Variable : apple
Fifth Variable : papaya
Explanation:
In the code snippet provided above, a tuple consisting of five elements has been created: mango, orange, banana, apple, and papaya. For reference, we have displayed the initialized tuple. Subsequently, we performed tuple unpacking by assigning each element from the tuple on the right to their corresponding variables on the left. Finally, we printed the values of the various initialized variables. Consequently, the tuple has been unpacked successfully, and the values have been assigned to the respective variables.
Note:While unpacking a tuple, the number of variables on left-hand side should be equal to the number of elements in a given tuple. In case, the variables do not match the size of the tuple, we can use an asterisk '*' in order to store the remaining elements as a list.
Looping Tuples
Python provides various methods to iterate over a tuple. Several of these methods include:
- Utilizing a 'for' loop
- Employing a 'while' loop
Python Looping Tuples Example
Below is a straightforward illustration demonstrating various methods to iterate over a Tuple in Python.
Example
# Python program to loop through a tuple
# creating a tuple
fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")
# printing the given tuple for reference
print("Given Tuple :", fruits_tuple)
print("Looping with 'for' Loop:")
i = 1
# iterating through the tuple
for fruit in fruits_tuple:
# printing the element
print(i, "-", fruit)
i += 1
print("\nLooping with 'while' Loop:")
# initializing an iterable with 0
j = 0
# using the while loop to iterate through the tuple
while j < len(fruits_tuple):
# printing the element of the tuple
print(j + 1, "-", fruits_tuple[j])
# incrementing the index value by 1
j += 1
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
Looping with 'for' Loop:
1 - mango
2 - orange
3 - banana
4 - apple
5 - papaya
Looping with 'while' Loop:
1 - mango
2 - orange
3 - banana
4 - apple
5 - papaya
Explanation:
In this instance, we have formed a tuple that includes several elements and displayed it for reference purposes. Subsequently, we employed both the 'for' loop and the 'while' loop to traverse each element within the tuple and output them. Consequently, the elements of the tuple are printed without any issues.
Tuple Operators in Python
The table below presents a compilation of various operators that can be utilized with Python tuples.
| S. No. | Python Operator | Python Expression | Result | Description |
|---|---|---|---|---|
1 |
+ | (2, 4, 6) + (3, 5, 7) | (2, 4, 6, 3, 5, 7) | Concatenation |
2 |
* | ('Apple', ) * 3 | ('Apple','Apple','Apple') | Repetition |
3 |
in, not in | 4 in (2, 4, 6, 8, 10) | True | Membership |
Python Example for Tuple Operators
Now, let us examine the subsequent example that demonstrates the application of various operators on Tuples in Python.
Example
# Python program to illustrate the use of operators in the case of tuples
# creating a tuple for concatenation
vegetables_tuple = ('Potato', 'Tomato', 'Onion')
# printing the tuple
print("Vegetables Tuple =>", vegetables_tuple)
# creating another tuple for concatenation
fruits_tuple = ('Mango', 'Apple', 'Orange')
# printing the tuple
print("Fruits Tuple =>", fruits_tuple)
# concatenating the tuples using the + operator
tuple_of_food_items = vegetables_tuple + fruits_tuple
# printing the resultant tuple
print("Concatenated Tuple: Tuple of Food Items =>", tuple_of_food_items)
# creating a tuple for repetition
sampleTuple = ('Mango', 'Grapes', 'Banana')
# printing the original tuple
print("Original tuple =>", sampleTuple)
# Repeating the tuple elements for 4 times using the * operator
sampleTuple = sampleTuple * 4
# printing the new tuple
print("New tuple =>", sampleTuple)
# creating a tuple for membership
test_tuple = (12, 23, 35, 76, 84)
# printing the tuple
print("Given tuple =>", test_tuple)
# test cases
n = 35
m = 47
# checking whether variable n and m belongs to the given tuple or not using the membership operator
if n in test_tuple:
print("Yes.", n, "is present in the tuple", test_tuple)
else:
print("No.", n, "is NOT present in the given tuple.")
if m in test_tuple:
print("Yes.", m, "is present in the tuple", test_tuple)
else:
print("No.", m, "is NOT present in the given tuple.")
Output:
Vegetables Tuple => ('Potato', 'Tomato', 'Onion')
Fruits Tuple => ('Mango', 'Apple', 'Orange')
Concatenated Tuple: Tuple of Food Items => ('Potato', 'Tomato', 'Onion', 'Mango', 'Apple', 'Orange')
Original tuple => ('Mango', 'Grapes', 'Banana')
New tuple => ('Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana')
Given tuple => (12, 23, 35, 76, 84)
Yes. 35 is present in the tuple (12, 23, 35, 76, 84)
No. 47 is NOT present in the given tuple.
Explanation:
In this illustration, we have utilized the concatenation operator '+' to merge the components of two distinct tuples into a new tuple. Additionally, we have employed the repetition operator '*' to duplicate the elements of the tuple a specified number of times. Furthermore, we have applied the membership operator 'in' to determine whether the provided item is included within the tuple.
Tuple Methods in Python
A Python tuple, defined as a sequence of unchangeable elements, poses challenges when it comes to altering or modifying the items that have been established within the tuple. Nevertheless, Python provides two inherent methods to facilitate interactions with tuples. These methods include the following:
- count
- index
We will now explore these methods comprehensively, accompanied by several examples for clarity.
The count Method
The count function is a native method in Python designed to tally the number of times a particular element appears within a tuple.
Syntax:
It has the following syntax:
tuple_name.count(item)
Parameter:
- item (mandatory): The item parameter represents the specific item that is to be located within the tuple.
- The frequency of occurrence of the designated item within the tuple.
Now, let us examine the subsequent example that demonstrates the application of the count method in the context of Python tuples.
Example
# Python program to demonstrate the use of count() method in the case of tuples
# creating tuples
T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
# counting the occurrence of 2 in the tuple T1
resultOne = T1.count(2)
# counting the occurence of 'Mango' in the tuple T2
resultTwo = T2.count('Mango')
# printing the results
print("Tuple T1 =>", T1)
print("Total Occurrence of 2 in T1 =>", resultOne)
# printing the results
print("\nTuple T2 =>", T2)
print("Total Occurrence of 'Mango' in T2 =>", resultTwo)
Output:
Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
Total Occurrence of 2 in T1 => 5
Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
Total Occurrence of 'Mango' in T2 => 4
Explanation:
In this illustration, we have utilized the count function to tally the frequency of specified elements within the provided tuple.
The index Method
The index function is a native method in Python that is utilized to locate a particular element within a tuple and provide its corresponding index.
Syntax:
It has the following syntax:
tuple_name.index(item)
Parameter:
- item (required): The item parameter is the item to be searched in the tuple.
- start (optional): The start parameter indicates the starting index from where the searching is begun.
- end (optional): The end parameter indicates the ending index till where the searching is done.
- An integer value that signifies the position of the initial appearance of the given value.
Now, let us examine the subsequent example that demonstrates the application of the index method in the context of Python tuples.
Example
# Python program to demonstrate the use of index() method in the case of tuples
# creating tuples
T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
# searching for the occurrence of 2 in the tuple T1
resultOne = T1.index(2)
resultTwo = T1.index(2, 5)
# searching for the occurence of 'Mango' in the tuple T2
resultThree = T2.index('Mango')
resultFour = T2.index('Mango', 3)
# printing the results
print("Tuple T1 =>", T1)
print("First Occurrence of 2 in T1 =>", resultOne)
print("First Occurrence of 2 after 5th index in T1 =>", resultTwo)
# printing the results
print("\nTuple T2 =>", T2)
print("First Occurrence of 'Mango' in T2 =>", resultThree)
print("First Occurrence of 'Mango' after 3rd index in T2 =>", resultFour)
Output:
Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
First Occurrence of 2 in T1 => 1
First Occurrence of 2 after 5th index in T1 => 5
Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
First Occurrence of 'Mango' in T2 => 2
First Occurrence of 'Mango' after 3rd index in T2 => 5
Explanation:
In this illustration, we have employed the index function to retrieve the index position of the initial appearance of the specified elements within the provided tuple.
Some Other Methods for Python Tuples
Apart from the count and index methods, we have some other methods to work with tuples in Python. These methods as follows:
- max
- min
- len
Let us now discuss these methods in detail.
The max Method:
The max function in Python is utilized to retrieve the highest value from a tuple.
Syntax:
It has the following syntax:
max(object)
Parameter:
- object (mandatory): The object parameter can be any iterable collection, including but not limited to Tuples, Lists, and similar structures.
- The most significant item from that iterable (such as a Tuple, List, and so forth)
Now, let's examine the subsequent example that demonstrates how to utilize the max function to identify the highest integer within the specified tuple.
Example
# Python program to demonstrate the use of max() method in the case of tuples
# creating a tuple
sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
# printing the tuple for reference
print("Given Tuple =>", sampleTuple)
# using the max() method to find the largest element in the tuple
largest_element = max(sampleTuple)
# printing the result for the users
print("The Largest Element in the Given Tuple =>", largest_element)
Output:
Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
The Largest Element in the Given Tuple => 9
Explanation:
In this illustration, we have employed the max function on the specified tuple to determine the highest element within it.
The min Method
Python includes a built-in function named min that can be utilized to determine the smallest value within a tuple.
Syntax:
It has the following syntax:
min(object)
Parameter:
- object (mandatory): The object parameter may consist of any iterable type, including but not limited to Tuple, List, etc.
- The least value from the provided iterable (such as a Tuple, List, etc.)
Now, let's examine the subsequent example that demonstrates how to utilize the min function to identify the smallest integer within the specified tuple.
Example
# Python program to demonstrate the use of min() method in the case of tuples
# creating a tuple
sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
# printing the tuple for reference
print("Given Tuple =>", sampleTuple)
# using the min() method to find the smallest element in the tuple
smallest_element = min(sampleTuple)
# printing the result for the users
print("The Smallest Element in the Given Tuple =>", smallest_element)
Output:
Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
The Smallest Element in the Given Tuple => 0
Explanation:
In this illustration, we have employed the min function on the specified tuple to identify the minimum element contained within it.
The len Method
The len function in Python is utilized to determine the length of a specified sequence, which can include collections like Tuples, Lists, Strings, and more.
Syntax:
It has the following syntax:
len(object)
Parameter:
- object (mandatory): The object parameter can be any iterable type, including Tuple, List, and so on.
- The count of items within that iterable (Tuple, List, etc.)
Now, let us examine the subsequent example that demonstrates how to utilize the len function to determine the length of a specific tuple.
Example
# Python program to demonstrate the use of len() method in the case of tuples
# creating a tuple
sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
# printing the tuple for reference
print("Given Tuple =>", sampleTuple)
# using the len() method to find the length of the tuple
length_of_tuple = len(sampleTuple)
# printing the result for the users
print("Number of Elements in the Given Tuple =>", length_of_tuple)
Output:
Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
Number of Elements in the Given Tuple => 10
Explanation:
In this instance, we utilized the len function on the specified tuple to determine the complete count of elements contained within it.
Conclusion
To sum up, the Python tuple is a fundamental data structure that enables the storage of a set of elements within one variable. In contrast to lists, tuples have the characteristic of being immutable, which indicates that their contents cannot be altered once they are formed. This immutability is beneficial when it is necessary to maintain the integrity of data throughout the execution of a program. Tuples can accommodate various data types, allow for indexing and slicing, and demonstrate greater memory efficiency compared to lists. Gaining proficiency in using tuples contributes to enhancing the dependability and efficiency of our Python programming.
Python Tuples - MCQs
- Which of the following is a correct way to create a tuple in Python?
- tpl_1 = [16, 2, 3]
- tpl_1 = {1, 2, 3}
- tpl_1 = (1, 2, 3)
- tpl_1 = <1, 2, 3>
- What is the main difference between a list and a tuple in Python?
- Tuples are faster and immutable
- Lists are immutable
- Tuples use more memory
- Lists can't be nested
- Which method can be used to count the number of times a value appears in a tuple?
- add
- count
- index
- find
Response: b) count
- What will the result of len((4, 5, 6)) be?
- Error
- Can tuples contain elements of different data types?
- Only strings
- Only integers