In Python, Tuple methods are built-in functions that we can use to perform different operations on tuples. These methods provides a convenient way for manipulating and analyzing tuple data.
Since tuple is an immutable collection of elements, there are only a few built-in methods available for us to work with. Unlike lists, we cannot add, remove, or sort elements in a tuple once it’s created.
The only two built-in methods that tuples support are:
count()
index()
We are now going to discuss these methods with the help of examples:
Tuple count() Method
The count() method is a built-in Python method that allow us to count the occurrence of the specified element in a tuple. This method takes a single argument as the element to be counted and returns its occurrence in the given tuple.
Syntax:
The syntax of the count() method is shown below:
tuple_name.count(item)
Parameter:
item (required):The item parameter is the element to be searched in the tuple.
Return:
The number of times the specified item appeared in the tuple.
Python Tuple count() Method Example
We are now going to look at a simple example showing the use of the tuple’s count() method in Python.
Example
# simple python program to show the use of the count() method
# given tuples
tuple_of_numbers = (1, 3, 4, 5, 2, 4, 6)
tuple_of_countries = ('Pakistan', 'USA', 'France', 'USA',
'Germany', 'Pakistan', 'Pakistan', 'Brazil', 'Japan')
print("Tuple 1:", tuple_of_numbers)
# counting the occurrence of 4
count_of_4 = tuple_of_numbers.count(4)
print("Count of 4:", count_of_4)
print() # empty line
print("Tuple 2:", tuple_of_countries)
# counting the occurrence of 'Pakistan'
Pakistan = tuple_of_countries.count('Pakistan')
print("Count of Pakistan:", Pakistan)
Here, we have used the count() method to find the total occurrences of the specified elements in the given tuples.
Python Example to count nested tuples and lists in Tuples
Let us now see another example showing the way of counting nested tuples and lists in Tuples.
Example
# python example to count nested tuples and lists
# given tuple
given_tuple = ((4, 5), 1, (4, 5), [4, 5], (2, ), 4, 5)
print("Given Tuple:", given_tuple)
# counting the tuple (4, 5) in given tuple
tpl_1 = given_tuple.count((4, 5))
print("Count of (4, 5):", tpl_1)
# counting the list [4, 5] in given tuple
lst_1 = given_tuple.count([4, 5])
print("Count of [4, 5]:", lst_1)
Output:
Given Tuple: ((4, 5), 1, (4, 5), [4, 5], (2,), 4, 5)
Count of (4, 5): 2
Count of [4, 5]: 1
Explanation:
Here, we have used the count() method to find the total occurrence of the specified tuple and list in the given tuple.
Tuple index() Method
The index() method is a built-in Python method allows us to search for a specified element in the tuple and return its position. We can also select an optional range in order to search a particular region in the tuple.
Syntax:
The syntax of the index() method is shown below:
tuple_name.index(item[, start[, stop]])
Parameter:
item (required): The item parameter is the element to be searched in the tuple.
start (optional): The start parameter specifies the starting index for the search.
end (optional): The end parameter specifies the ending index.
Return:
An Integer Value indicating the index of the first occurrence of the specified value.
Note: This method is raise a ValueError exception if the specified element is not found in the tuple.
Python Tuple index() method Example
We are now going to see a simple example to understand the working of the tuple’s index() method in Python.
Example
# simple python program to show the use of the index() method
# given tuple
tuple_of_fruits = ('orange', 'apple', 'banana', 'mango',
'apple', 'melon', 'cherries', 'grapes')
print("Given Tuple:", tuple_of_fruits)
# getting the index of 'apple'
idx_of_apple = tuple_of_fruits.index('apple')
print("First occurrence of 'apple':", idx_of_apple)
# getting the index of 'apple' after 3rd index
idx_of_apple = tuple_of_fruits.index('apple', 3)
print("First occurrence of 'apple' after 3rd index:", idx_of_apple)
Output:
Given Tuple: ('orange', 'apple', 'banana', 'mango', 'apple', 'melon', 'cherries', 'grapes')
First occurrence of 'apple': 1
First occurrence of 'apple' after 3rd index: 4
Explanation:
Here, we have used the index() method to find the first appearance of the specified elements in the given tuple.
Python Tuple index() Method Example Without Any Element
Let us see an example showing what will happen if the element does not exist in the given tuple.
Example
# example to find element that is not found in the tuple
# given tuple
tpl_1 = (1, 3, 4, 5, 6, 2, 7, 4, 9, 1)
# getting the index of 8
idx_of_8 = tpl_1.index(8)
Output:
ValueError: tuple.index(x): x not in tuple
Explanation:
Here, we can observe that the index() method has raised the ValueError exception as the specified element is not found in the given tuple.
Python Tuple Methods FAQs
1. Do tuples have methods in Python?
Yes, Python tuples have two built-in methods:
count(): This method is used to return the number of times the specified element appears in the tuple.
index(): This method is used to return the first index of the specified element in the tuple. It raises a ValueError exception if the element is not found.
2. Why are there only a few methods available for tuples?
Tuple is an immutable data type, meaning we cannot change its content once created. Most list methods, like append() or remove(), modify data, so they are not available for tuples.
3. Can we add or remove items from a tuple?
No, we cannot directly add or remove elements from a tuple because it is immutable. However, we can create a new tuple by combining the existing ones, as shown in the following example:
Example
# given tuple
tpl_1 = (1, 3, 5, 2)
# creating a new tuple
tpl_2 = tpl_1 + (4,)
print(tpl_2)
Output:
(1, 3, 5, 2, 4)
4. How to convert a tuple to a list to modify it?
We can make use of the list() function to convert a given tuple to a list, make changes, and then convert it back.
Here is an example showing the way of converting a tuple to a list:
Example
# given tuple
tpl_1 = (1, 3, 5, 2)
# converting tuple to a list
lst_1 = list(tpl_1)
lst_1.append(4) # making changes
# converting list back to a tuple
tpl_1 = tuple(lst_1)
print(tpl_1)
Output:
(1, 3, 5, 2, 4)
5. Can we store mutable elements like lists inside a tuple?
Yes, but we need to be cautious while storing mutable elements like lists inside a tuple. The tuple itself remains immutable; however, we can change the mutable elements like the list inside it.
Let us see an example:
Example
# given tuple
tpl_1 = ([1, 3], 5)
# changing list inside the tuple
tpl_1[0].append(2)
print(tpl_1)
Tuple is a built-in data structure in Python for storing a collection of objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and repetition; however, the main difference between both is that the tuples in Python are immutable, unlike the Python list which is mutable.
Let us see a simple example of initializing a tuple in Python.
Example
# creating a tuple
T = (20, 'Learn Python', 35.75, [20, 40, 60])
print(T)
Output:
(20, 'Learn Python', 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] = ‘TpointTech’ (String)
T[2] = 35.75 (Float)
T[3] = [20, 40, 60] (Nested List)
Characteristics of Python Tuples
Tuple in Python is a data structure, which is
Ordered: Each data element in a tuple has a particular order that never changes.
Immutable: The data elements of tuple cannot be changed once initialized.
Let us take a look at the following example showing that Tuples are immutable.
Example
# creating a tuple
my_tpl = (25, 16.25, 'Learn Python', [20, 40, 60], 3e8)
print(my_tpl)
# trying to changing the element of the tuple
# my_tpl[1] = 'welcome' # raise TypeError
All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.
Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.
Let us consider the following example demonstrating the inclusion of different data types in 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, "Tpointtech", 17.43)
print("Tuple with different data types: ", mix_tpl)
# Creating a nested tuple
nstd_tpl = ("Tpointtech", {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, 'Tpointtech', 17.43)
A nested tuple: ('Tpointtech', {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))
Explanation:
In the above snippet of code, we have created four different tuples containing different types of elements. The first tuple is an empty tuple defined using the parentheses with no element in between. After that, we have defined an integer tuple consisting of 6 integer values between the parentheses separated by the commas. The third tuple is comprised of three objects of different data types – integer, string, and float. At last, we have defined a tuple as a different object, including another tuple.
Accessing Tuple Elements
In Python, we can access any object of a tuple using indices. The objects or elements of a tuple can be accessed by referring to the index number, inside of square brackets ‘[]’.
Let us consider the following example illustrating how to access an element of a tuple using 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])
In the above example, we have created a tuple consisting of six elements. We have then used the indexing to access the different elements of the tuple.
Slicing in Tuple
Slicing a tuple means dividing a tuple into smaller tuples with the help of indexing. In order to slice a tuple, we need to specify the starting and ending index value, that will return a new tuple with the specified objects.
We can slice a tuple using the colon ‘:’ operator separating the start and end index as shown below:
Syntax:
It has the following syntax:
tuple[start:end]
Python Tuple Slicing Example
Let us consider a simple example showing the way of slicing 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 example, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have printed the tuple of elements ranging from 1 to 5 using the slicing method. We have then printed the elements ranging from 0 to -3 using the negative indexing in slicing. At last, we have printed the entire tuple using the colon ‘:’ operator only without specifying the start and end index values.
Deleting a Tuple
Unlike lists, tuples are immutable data types meaning that we cannot update the objects of a tuple once it is created. Therefore, removing the elements of the tuple is also not possible. However, we can delete the entire tuple using the ‘del’ keyword as shown below.
Syntax:
It has the following syntax:
del tuple_name
Python Example to Delete a Tuple
Let us consider the following snippet of code illustrating the method of deleting a tuple with the help of the ‘del’ keyword. Here is a simple example showing the way 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:
Here, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then printed the entire tuple for reference. After that, we have used the try and except blocks to delete a particular element from the tuple using the del keyword. As a result, an exception has been raised saying ‘tuple’ object doesn’t support item deletion. We have then used the del keyword to delete the entire tuple and tried printing it. As a result, we can observe another exception saying name ‘sampleTuple’ is not defined.
Changing the Elements in Tuple
Once we create a tuple, it is impossible for us to change its elements due its immutable nature. However, there is a way to update the elements of a tuple. We can convert the tuple into a list, change the list, and convert the list back into a tuple.
Python Example to Change the Element in Tuple
Let us see a simple example showing the way of updating elements of 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 example, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have converted the tuple into a list using the list() method. We have then changed the element at index 2 of the list to ‘grapes’ and used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element at index 2 also changed from ‘banana’ to ‘grapes’ respectively.
Adding Elements to a Tuple
Since Tuple is an immutable data type, it does not have the built-in append() method to add the elements. However, there are few ways we can use in order to add an element to a tuple.
Converting the Tuple into a List
In order to add a new element to a tuple, we can follow a similar approach we used while changing the element in a tuple. The approach follows the steps discussed below:
Step 1: Convert the Tuple into a List.
Step 2: Add the required element to the list using the append() method.
Step 3: Convert the List back into the Tuple.
Let us consider the following snippet of code, demonstrating the same.
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 above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have convert the tuple into a list using the list() method. We have then added a new element ‘blueberry’ in the list using the append() method. After that, we have used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘blueberry’ has been added to the given tuple respectively.
Adding a Tuple to a Tuple
In Python, we are allowed to add multiple tuples to tuples. Therefore, if we want to insert a new element to a tuple, we can follow the steps as shown below:
Step 1: Create a new Tuple with the element(s) we want to add.
Step 2: Adding the new tuple to the existing tuple.
Let us consider the following example, illustrating the same.
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 above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have created a new tuple consisting of another element ‘blueberry’. After that, we have added the new tuple to the existing tuple using the ‘+’ operator. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘pineapple’ has been added to the given tuple respectively.
Unpacking Tuples
While initializing a tuple, we generally assign objects to it. This process is known as ‘packing’ a tuple. However, Python offers us an accessibility to extract the objects back into variables. This process of extracting the objects from a tuple and assign them to different variables is known as ‘unpacking’ a tuple.
Python Example for Unpacking Tuples
Let us consider the following example illustrating the way 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 above snippet of code, we have created a tuple of five elements – mango, orange, banana, apple, and papaya. We have printed the initialized tuple for reference. After that, we have unpacked the tuple by assigning each element of the tuple at right to their corresponding variables at left. At last, we have printed the values of different initialized variables. As a result, the tuple is unpacked successfully, and the values are assigned to the 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 offers different ways to loop through a tuple. Some of these ways are as follows:
Using ‘for’ loop
Using ‘while’ loop
Python Looping Tuples Example
Here is a simple example showing the ways of looping through 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 example, we have created a tuple containing some elements and printed it for reference. We have then used the ‘for’ and ‘while’ loop to iterate through each element of tuple and printed them. As a result, the elements of the tuple are printed successfully.
Tuple Operators in Python
The following table displays the list of different operators to work 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
Let us now consider the following example illustrating the use of different 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 example, we have used the concatenation operator ‘+’, to add the elements of two different tuples in a new tuple. We have used the repetition operator ‘*’ to repeat the elements of the tuple for given number of times. We have also used the membership operator ‘in’ to check if the passed item is a member of the tuple.
Tuple Methods in Python
Python tuple, being a collection of immutable items, makes it difficult to alter or modify the initialized objects of the tuple. However, Python offers two built-in methods to work with tuples. These methods are as listed below:
count()
index()
Let us now discuss these methods in detail with the help of some examples.
The count() Method
The count() method is a built-in Python method to count the occurrence of the specified element in a tuple.
Syntax:
It has the following syntax:
tuple_name.count(item)
Parameter:
item (required): The item parameter is the item to be searched in the tuple.
Return:
The number of times the specified item appeared in the tuple.
Let us now look at the following example illustrating the use of the count() method in the case 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 example, we have used the count() method to count the occurrence of passed variables in the given tuple.
The index() Method
The index() method is a built-in Python method to search for a specified element in the tuple and return its position.
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.
Return:
An Integer Value indicating the index of the first occurrence of the specified value.
Let us now look at the following example illustrating the use of the index() method in the case 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 example, we have used the index() method to return the index value of the first occurrence of the passed elements in the given 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:
Python’s max() method is used to return the maximum value in the tuple.
Syntax:
It has the following syntax:
max(object)
Parameter:
object (required): The object parameter can be any iterable such as Tuple, List, etc.
Return:
The largest element from that iterable (Tuple, List, etc.)
Let us now consider the following example illustrating the use of the max() method to find the largest integer in the given 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 the example, we have used the max() method on the given tuple to find the largest element in it.
The min() Method
Python provides a method called min() to find the minimum value in the tuple.
Syntax:
It has the following syntax:
min(object)
Parameter:
object (required): The object parameter can be any iterable such as Tuple, List, etc.
Return:
The smallest element from that iterable (Tuple, List, etc.)
Let us now consider the following example illustrating the use of the min() method to find the smallest integer in the given 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 the example, we have used the min() method on the given tuple to find the smallest element in it.
The len() Method
Python’s len() method is used to find the length of the given sequence such as Tuple, List, String, etc.
Syntax:
It has the following syntax:
len(object)
Parameter:
object (required): The object parameter can be any iterable such as Tuple, List, etc.
Return:
The number of elements in that iterable (Tuple, List, etc.)
Let us now consider the following example illustrating the use of the len() method to find the length of the given 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 the example, we have used the len() method on the given tuple to find the total number of elements present in it.
Conclusion
In conclusion, Python tuple is an essential data structure that allows us to store a collection of items in a single variable. Unlike lists, tuples are immutable, meaning their values cannot be changed after creation. They are useful when we want to ensure data remains constant throughout the program. Tuples can store multiple data types, support indexing and slicing, and are more memory-efficient than lists. Understanding how to use tuples helps improve the reliability and performance of our Python code.
Python Lists offers a wide range of built-in methods to manipulate data efficiently. List in Python, is an ordered and mutable data type allowing us to store multiple values in a single variable.
Let us take a look at various List methods available in Python.
Method
Description
append()
This method is utilized to add an element x to the end of the list.
extend()
This method is utilized to add all elements of an iterable (list, tuple, etc.) to the list.
insert()
This method is utilized to insert an element x at index i.
remove()
This method is utilized to remove the first occurrence of x. It raises ValueError if x is not found.
pop()
This method is utilized to remove and returns the element at index i (default is the last element).
clear()
This method is utilized to remove all elements, making the list empty.
index()
This method is utilized to return the first index of x between start and end. It raises ValueError if not found.
count()
This method is utilized to return the number of occurrences of x in the list.
sort()
This method is utilized to sort the list in place (default is ascending).
reverse()
This method is utilized to reverse the order of the list in place.
copy()
This method is utilized to return a shallow copy of the list.
1) append()
The append() method in Python allows us to add an element at the end of the list.
Syntax:
It has the following syntax:
list_name.append(item)
Python append() Method Example
Let us take an example to demonstrate the append() method in Python.
Example
# python program to show the use of list append() method
# creating a list
list_of_fruits = ['apple', 'mango', 'banana', 'orange', 'guava']
# printing the list
print("List of Fruits:", list_of_fruits)
# using the append() method
list_of_fruits.append('grapes')
# printing the updated list
print("Updated List of Fruits:", list_of_fruits)
Output:
List of Fruits: ['apple', 'mango', 'banana', 'orange', 'guava']
Updated List of Fruits: ['apple', 'mango', 'banana', 'orange', 'guava', 'grapes']
Explanation:
In the above example, we have used the append() method to add a new element ‘grapes’ at the end of the given list.
2) extend()
The extend() method in Python allows us to append all the elements from an iterable (list, tuple, set, etc.) at the end of the list.
Syntax:
It has the following syntax:
list_name.extend(iterable)
Python extend() Method Example
Let us take an example to demonstrate the extend() method in Python.
Example
# python program to show the use of list extend() method
# initializing the lists
shopping_list = ['milk', 'bread', 'butter']
new_items = ['eggs', 'apples', 'coffee']
# printing the lists
print("Old Shopping List:", shopping_list)
print("New Items:", new_items)
# using the extend() method
shopping_list.extend(new_items)
# printing the updated list
print("Updated Shopping List:", shopping_list)
Output:
Old Shopping List: ['milk', 'bread', 'butter']
New Items: ['eggs', 'apples', 'coffee']
Updated Shopping List: ['milk', 'bread', 'butter', 'eggs', 'apples', 'coffee']
Explanation:
In the above example, we have used the extend() method to add an iterable at the end of the given list.
3) insert()
The insert() method in Python allows us to insert an the elements at a specified position in the list.
Syntax:
It has the following syntax:
list_name.insert(index, item)
Python insert() Method Example
Let us take an example to illustrate how the insert() method works in Python.
Example
# python program to show the use of list insert() method
# initializing the list
shopping_list = ['milk', 'bread', 'butter', 'coffee']
# printing the list
print("Old Shopping List:", shopping_list)
# using the insert() method
shopping_list.insert(2, 'eggs')
# printing the updated list
print("New Shopping List:", shopping_list)
Output:
Old Shopping List: ['milk', 'bread', 'butter', 'coffee']
New Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
Explanation:
In the above example, we have used the insert() method to insert item ‘eggs’ at the second index of the given list.
4) remove()
The remove() method in Python allows us to remove the first occurrence of the specified element from the list.
Syntax:
It has the following syntax:
list_name.remove(item)
Python remove() Method Example
Let us take an example to demonstrate the remove() method in Python.
Example
# python program to show the use of list remove() method
# initializing the list
shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']
# printing the list
print("Old Shopping List:", shopping_list)
# using the remove() method
shopping_list.remove('butter')
# printing the updated list
print("New Shopping List:", shopping_list)
Output:
Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
New Shopping List: ['milk', 'bread', 'eggs', 'coffee']
Explanation:
In the above example, we have used the remove() method to remove item ‘butter’ from the given list.
5) pop()
The pop() method in Python allows us to remove and return the element from the specified index of the given list.
Syntax:
It has the following syntax:
list_name.pop(index)
Python pop() Method Example
Let us take an example to demonstrate the pop() method in Python.
Example
# python program to show the use of list pop() method
# initializing the list
shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']
# printing the list
print("Old Shopping List:", shopping_list)
# using the pop() method
popped_item = shopping_list.pop(1)
# printing the updated list
print("New Shopping List:", shopping_list)
print("Popped Item:", popped_item) # popped element
Output:
Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
New Shopping List: ['milk', 'eggs', 'butter', 'coffee']
Popped Item: bread
Explanation:
In the above example, we have used the pop() method to remove and return the item at index ‘2’ from the given list.
6) clear()
The clear() method in Python allows us to remove all the elements from the list making it empty.
Syntax:
It has the following syntax:
list_name.clear()
Python clear() Method Example
Let us take an example to demonstrate the clear() method in Python.
Example
# python program to show the use of list clear() method
# initializing the list
shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']
# printing the list
print("Old Shopping List:", shopping_list)
# using the clear() method
shopping_list.clear()
# printing the updated list
print("New Shopping List:", shopping_list)
Output:
Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
New Shopping List: []
Explanation:
In the above example, we have used the clear() method to remove all the elements from the given list.
7) index()
The index() method in Python returns the first index of the element within start and end.
Syntax:
It has the following syntax:
list_name.index(item, start, end)
Python index() Method Example
Let us take an example to demonstrate the index() method in Python.
Example
# python program to show the use of list index() method
# initializing the list
shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']
# printing the lists
print("Shopping List:", shopping_list)
# using the index() method
item_index = shopping_list.index('butter')
# printing the index of the item
print("Index of butter:", item_index)
Output:
Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
Index of butter: 3
Explanation:
In the above example, we have used the index() method to find the first occurrence of the element from the given list.
8) count()
The count() method in Python allows us to all the occurrence of the element in the list.
Syntax:
It has the following syntax:
list_name.count(item)
Python count() Method Example
Let us take an example to demonstrate the count() method in Python.
Example
# python program to show the use of list count() method
# initializing the list
shopping_list = ['milk', 'bread', 'egg', 'milk', 'butter', 'coffee', 'egg', 'flour', 'egg']
# printing the lists
print("Shopping List:", shopping_list)
# using the count() method
item_count = shopping_list.count('egg')
# printing the count of the item
print("No. of Eggs:", item_count)
In the above example, we have used the count() method to find all the occurrences of ‘egg’ in the given list.
9) sort()
The sort() method in Python allows us to sort the list in place.
Syntax:
It has the following syntax:
list_name.sort(reverse = False, key = None)
Python sort() Method Example
Let us take an example to illustrate how the sort() method works in Python.
Example
# python program to show the use of list sort() method
# initializing the list
fruit_basket = ['mango', 'apple', 'orange', 'banana', 'grapes']
# printing the list
print("Unsorted Fruit Basket:", fruit_basket)
# using the sort() method
fruit_basket.sort()
# printing the updated list
print("Sorted Fruit Basket:", fruit_basket)
Output:
Unsorted Fruit Basket: ['mango', 'apple', 'orange', 'banana', 'grapes']
Sorted Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
Explanation:
In the above example, we have used the sort() method to sort the elements of the given list in ascending order.
10) reverse()
The reverse() method in Python allows us to reverse the list in place.
Syntax:
It has the following syntax:
list_name.reverse()
Python reverse() Method Example
Let us take an example to illustrate how the reverse() method works in Python.
Example
# python program to show the use of list reverse() method
# initializing the list
fruit_basket = ['apple', 'banana', 'grapes', 'mango', 'orange']
# printing the list
print("Fruit Basket:", fruit_basket)
# using the reverse() method
fruit_basket.reverse()
# printing the updated list
print("Reversed Fruit Basket:", fruit_basket)
Output:
Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
Reversed Fruit Basket: ['orange', 'mango', 'grapes', 'banana', 'apple']
Explanation:
In the above example, we have used the reverse() method to reverse the given list.
11) copy()
The copy() method in Python allows us to create a shallow copy of the list.
Syntax:
It has the following syntax:
list_name.copy()
Python copy() Method Example
Let us take an example to illustrate how the copy() method works in Python.
Example
# python program to show the use of list copy() method
# initializing the list
fruit_basket = ['apple', 'banana', 'grapes', 'mango', 'orange']
# printing the list
print("Fruit Basket:", fruit_basket)
# using the copy() method
new_fruit_basket = fruit_basket.copy()
# printing the copied list
print("Copied Fruit Basket:", new_fruit_basket)
Output:
Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
Copied Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
Explanation:
In the above example, we have used the copy() method to create a shallow copy of the given list.
In Python, a list is a built-in data structure that allows us to store multiple items in a single variable. Lists are one of the most used data structures in Python because they are mutable, ordered, and can hold different types of elements. Lists provide a flexible way to handle collections of data and come with many useful built-in methods.
Let us take a look at a simple example of a list.
Example
# creating a list
L = [20, 'Python App', 35.75, [20, 40, 60]]
print(L)
Output:
[20, 'Python App', 35.75, [20, 40, 60]]
Explanation:
In the above example, we have created a simple list consisting of four elements of different data types. Each element in this list is indexed, meaning it can be accessed using its position in the list, as shown below:
L[0] = 20 (Integer)
L[1] = ‘Python App’ (String)
L[2] = 35.75 (Float)
L[3] = [20, 40, 60] (Nested List)
Characteristics of Python Lists
List in Python is a data structure, which is:
Ordered: The data elements of list maintain their order of insertion. If an element is inserted at a specific index, it remains there unless it is explicitly changed.
Changeable (Mutable): Lists in Python allow modification of their elements after creation.
Let us look at the following example showing that Lists are changeable.
Example
# creating a list
my_lst = [25, 16.25, 'Python App', [20, 40, 60], 3e8]
# changing the element of the list
my_lst[1] = 'welcome'
print(my_lst)
In the above example, we have created three types of lists – empty list, list consisting of only integer values, and list consisting of elements of different data types. We have then printed them for reference.
Accessing List Elements
Elements in a list can be accessed using indexing. Python uses zero-based indexing, meaning the first element has an index of 0. We can use the index number enclosed with the square brackets ‘[]’ to access the element present at the given position.
Here is an example showing the method of accessing the element in a given list.
In the above example, we have created three types of lists – empty list, list consisting of only integer values, and list consisting of elements of different data types. We have then printed them for reference.
Adding Elements to the List
Python offers accessibility to add elements to a list. This can be achieved using the various options available for us:
append(): Adds a single element to the end of the list.
insert(): Inserts an element at a specific index.
extend(): Adds multiple elements to the end of the list.
Here is an example showing different methods to add elements to a list.
Example
# creating a list
my_lst = [7, 3, 4]
# Method 1: using append()
my_lst.append(6)
print(my_lst)
# Method 2: using insert()
my_lst.insert(1, 13)
print(my_lst)
# Method 3: using extend()
my_lst.extend([14, 43, 37])
print(my_lst)
In the above example, we have created a list and used three different methods – append(), insert() and extend(), in order to insert items in the list. As a result, the append() method has added an item at the end of the list. The insert() method has added an item at the second place in the list. The extend() method has added multiple elements altogether at the end of the list.
Updating Elements into a List
Elements in a list can be updated using indexing. The following is an example showing the way of updating items in a list.
Example
# creating a list
my_lst = [17, 23, 35]
# Updating the second element
my_lst[1] = 52
print(my_lst)
Output:
[17, 52, 35]
Explanation:
In the above example, we have created a list. We then used the indexing to update the second element of the list.
Removing Elements from the List
Python provides several methods to remove elements from a list:
remove(value): Removes the first occurrence of the value.
pop(index): Removes the element at a specific index (or the last element by default).
del statement: Deletes an element or the entire list.
Let us take a look at the following example showing several ways to remove an item from the list.
Example
# creating a list
my_lst = [14, 25, 43, 2, 33]
# Method 1: using remove()
my_lst.remove(43)
print(my_lst)
# Method 2: using pop()
my_lst.pop(-1)
print(my_lst)
# Method 3: using del keyword
del my_lst[0]
print(my_lst)
Output:
[14, 25, 2, 33]
[14, 25, 2]
[25, 2]
Explanation:
In the above example, we have created a list and used three different approaches – remove(), pop() and del keyword, in order to remove items from the list. As a result, remove() method has removed the specified item from the list. The pop() method has removed the element at the specified index from the list. The del keyword has deleted the element from the list at the specified index.
Iterating Over Lists
In Python, we can iterate over lists using the loops. Let us take an example showing the use of ‘for’ loop and ‘while’ loop to iterate over the elements of a given list.
Example
# creating a list
my_lst = [12, 23, 9, 17, 41]
print("Iterating List using 'for' loop:")
# Using for loop
for ele in my_lst:
print(ele)
print("\nIterating List using 'while' loop:")
# Using while loop
i = 0
while i < len(my_lst):
print(my_lst[i])
i += 1
Output:
Iterating List using 'for' loop:
12
23
9
17
41
Iterating List using 'while' loop:
12
23
9
17
41
Explanation:
In this example, we have created a list. We have then used the for loop to iterate over the list. We then used the while loop where we set the initial index value, i as 0; and incremented it while printing the element of the current index from the list.
Nested Lists in Python
Nested List is a list in Python that consists of multiple sub-lists separated by commas. The elements in each sub-list can be of different data types. The inner lists (or sub-list) can again consist of other lists, giving rise to the multiple levels of nesting.
In Python, we can use nested lists to create hierarchical data structures, matrices or simply, a list of lists. Python provides various tools to handle nested lists efficiently and effectively, allowing users to perform standard functions on them.
Let us see an example showing the different operations on nested list in Python.
Example
# creating a nested list
nested_lst = [[14, 6, 8], [13, 18, 25], [72, 48, 69]]
print("Nested List:", nested_lst)
print("\nAccessing Elements of Nested List:")
# Accessing elements
print("nested_lst[0]:", nested_lst[0])
print("nested_lst[0][1]:", nested_lst[0][1])
print("\nIterating through Nested list using 'for' loop:")
# Iterating through a nested list
for sublist in nested_lst:
for item in sublist:
print(item)
print("\nAdding element to Nested list:")
# Adding elements
nested_lst[0].append(10)
print("New Nested List:", nested_lst)
Output:
Nested List: [[14, 6, 8], [13, 18, 25], [72, 48, 69]]
Accessing Elements of Nested List:
nested_lst[0]: [14, 6, 8]
nested_lst[0][1]: 6
Iterating through Nested list using 'for' loop:
14
6
8
13
18
25
72
48
69
Adding element to Nested list:
New Nested List: [[14, 6, 8, 10], [13, 18, 25], [72, 48, 69]]
Explanation:
In the above example, we have created a nested list. We then used the indexing to access the elements of the list. In first case, we have accessed the element of the outer list using nested_lst[0], which returns the inner list as an output, i.e., [14, 6, 8]. In second case, we have accessed the element of the inner list using nested_lst[0][1], which returns the element of the inner list, i.e., 6. We then perform iteration on the nested list using the nested for loop. At last, we have added an element to the nested list using the append() method.
Finding the Length of a List
Python provides a built-in function called len() in order to determine the number of elements in a list.
Syntax:
len(list_name)
Let us take an example showing the use of the len() function on lists.
Example
# creating a list
lst_one = [15, 61, 23, 6, 87, 5, 93]
# using the len() function to find the size of the list
no_of_ele = len(lst_one)
print("Given List:", lst_one)
print("Number of Elements in the given list:", no_of_ele)
Output:
Given List: [15, 61, 23, 6, 87, 5, 93]
Number of Elements in the given list: 7
Explanation:
In the above example, we have created a list of some integers. We have then used the len() function to find the size of the list and store it in a variable. We then printed the list and the variable value as a result.
Sorting a List
Python provides a method called sort() that allows users to sort the elements of a list in place. Let us look at an example showing the working of sort() method.
Example
# creating a list
lst_one = [15, 61, 23, 6, 87, 5, 93]
print("Given List:", lst_one)
# sorting the list in ascending order (by default)
lst_one.sort()
print("Sorted List:", lst_one)
In the above example, we have created a list and used the reverse() method to reverse the order of the elements in the given list.
Finding the Largest and Smallest Number in a List
To find the largest and smallest number in a list, we can make use of max() and min() functions as shown in the following example:
Example
# creating a list
lst_one = [15, 61, 23, 6, 87, 5, 93]
print("Given List:", lst_one)
# finding largest and smallest number
print("Largest Number:", max(lst_one))
print("Smallest Number:", min(lst_one))
Output:
Given List: [15, 61, 23, 6, 87, 5, 93]
Largest Number: 93
Smallest Number: 5
Explanation:
In the above example, we have created a list. We then used the max() function to determine the largest number in the given list. We also used the min() function to find the smallest number.
Calculating Sum of Elements in a List
In order to calculate the sum of elements in a list, we can use Python’s built-in sum() function as shown in the following example:
Example
# creating a list
lst_one = [15, 61, 23, 6, 87, 5, 93]
print("Given List:", lst_one)
# finding sum of the elements in the list
print("Sum of the Elements in the list:", sum(lst_one))
Output:
Given List: [15, 61, 23, 6, 87, 5, 93]
Sum of the Elements in the list: 290
Explanation:
In the above example, we have created a list. We then used the sum() function to calculate the sum of the elements in the given list.
Conclusion
Python lists provide a versatile way to handle multiple data items. With functionalities like appending, inserting, updating, and iterating, lists form the backbone of many Python programs. Mastering lists is essential for efficient programming in Python.