PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
UNIT IV LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters;
Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced list processing
- list comprehension; Illustrative programs: simple sorting, histogram, Students marks statement, Retail bill
preparation.
1. PYTHON LIST
1.1 INTRODUCTION
List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed
in square brackets [ ]. List is an ordered collection of items. The items in a Python list need not be of the same
data type. Each item in a list has a unique position index, starting from 0. A list in Python is similar to an array
in C, C++ or Java. However, the major difference is that in C/C++/Java, the array elements must be of same
type. On the other hand, Python lists may have objects of different data types. Following are some examples
of Python lists:
list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list4 = [25.50, True, -55, 1+2j]
In Python, a list is a mutable, ordered collection of elements that can hold items of any data type (e.g.,
integers, strings, floats, other lists, etc.). Lists are one of the most commonly used data structures in Python
due to their flexibility and ease of use.
1.2 CHARACTERISTICS OF A PYTHON LIST
• Ordered: The order of elements is preserved. Lists maintain the sequence in which elements are
inserted.
• Mutable: Lists can be changed after creation (i.e., you can modify, add, or remove elements).
• Indexed: Each element in the list has a unique index, starting from 0 for the first element.
• Heterogeneous: Lists can contain elements of different types.
1.3 SYNTAX FOR LIST
The syntax for creating a list in Python is straightforward. The basic syntax is:
list_name = [element1, element2, element3, ...]
• list_name: The variable name that will hold the list.
• []: Square brackets are used to define the list.
• element1, element2, ...: Elements separated by commas inside the square brackets.
Examples:
a. List with integers: numbers = [1, 2, 3, 4, 5]
b. List with mixed data types: mixed_list = [10, "Hello", 3.14, True]
c. Empty list: empty_list = []
d. List with other lists (nested lists): nested_list = [1, [2, 3], 4]
1.4 LIST WITH LIST COMPREHENSION
A list can also be created using a list comprehension, which provides a short way to create lists by applying
an expression to each item in an iterable.
squared_numbers = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
GE3151 Problem Solving and Python Programming 1
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
1.5 INDEX OPERATOR [ ]
The index operator [ ] in Python is used to access individual elements of a sequence, such as a list, string,
tuple, or other indexable data types. It allows direct access to elements based on their position in the sequence,
using an index.
1.5.1 Usage of the Index Operator [ ]
a. Accessing Elements
• You can retrieve elements from a sequence using their index.
• Indexing starts from 0 for the first element, 1 for the second, and so on.
my_list = [10, 20, 30, 40]
print(my_list[0]) # Access first element: 10
print(my_list[2]) # Access third element: 30
b. Negative Indexing
• Negative indices allow access to elements from the end of the sequence.
• -1 refers to the last element, -2 to the second last, and so on.
my_list = [10, 20, 30, 40]
print(my_list[-1]) # Access last element: 40
print(my_list[-2]) # Access second last element: 30
c. Indexing Strings
• Strings are sequences of characters, and you can use the index operator to access individual characters.
my_string = "Python"
print(my_string[0]) # First character: 'P'
print(my_string[-1]) # Last character: 'n'
print(my_string[2:5]) # Slice 'tho'
d. Modifying Lists
• The index operator can also be used to modify list elements (since lists are mutable).
my_list = [10, 20, 30, 40]
my_list[2] = 99 # Change the third element
print(my_list) # Output: [10, 20, 99, 40]
e. IndexError
• Accessing an index outside the range of the sequence raises an IndexError.
my_list = [10, 20, 30]
print(my_list[5]) # IndexError: list index out of range
1.6 BASIC LIST OPERATIONS
a. Creating a List
• Lists can store multiple items of any data type, including numbers, strings, or even other lists.
my_list = [1, 2, 3, 4, 5] # List of integers
mixed_list = [1, "Hello", 3.5, True] # List with mixed data types
b. Accessing Elements
• Use the index operator [ ] to access individual elements.
print(my_list[0]) # First element: 1
print(my_list[-1]) # Last element: 5
c. Modifying Elements
• Lists are mutable, so you can change their elements.
my_list[2] = 99 # Change the third element
GE3151 Problem Solving and Python Programming 2
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
print(my_list) # Output: [1, 2, 99, 4, 5]
d. Adding Elements
You can add elements to a list using the following methods:
• append(): Adds a single element at the end of the list.
my_list.append(6)
print(my_list) # Output: [1, 2, 99, 4, 5, 6]
• extend(): Adds multiple elements at the end of the list.
my_list.extend([7, 8])
print(my_list) # Output: [1, 2, 99, 4, 5, 6, 7, 8]
• insert(): Adds an element at a specific position.
my_list.insert(2, 50) # Insert 50 at index 2
print(my_list) # Output: [1, 2, 50, 99, 4, 5, 6, 7, 8]
e. Removing Elements
• remove(): Removes the first occurrence of a value.
my_list.remove(99)
print(my_list) # Output: [1, 2, 50, 4, 5, 6, 7, 8]
• pop(): Removes an element by index (default is the last).
my_list.pop(2) # Remove the element at index 2
print(my_list) # Output: [1, 2, 4, 5, 6, 7, 8]
• clear(): Removes all elements from the list.
my_list.clear()
print(my_list) # Output: []
f. Searching for Elements
• in operator: Checks if an element exists in the list.
print(5 in my_list) # Output: True
• index(): Returns the index of the first occurrence of an element.
my_list = [1, 2, 3, 4, 5]
print(my_list.index(3)) # Output: 2
7. Sorting and Reversing
• sort(): Sorts the list in ascending order.
my_list = [5, 2, 8, 1]
my_list.sort()
print(my_list) # Output: [1, 2, 5, 8]
• reverse(): Reverses the elements of the list.
my_list.reverse()
print(my_list) # Output: [8, 5, 2, 1]
8. Copying a List
• copy(): Creates a shallow copy of the list.
new_list = my_list.copy()
print(new_list) # Output: [8, 5, 2, 1]
10. Finding the Length
• len(): Returns the number of elements in the list.
print(len(my_list)) # Output: 6
11. Combining Lists
• + operator: Concatenates two lists.
list1 = [1, 2, 3]
GE3151 Problem Solving and Python Programming 3
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
1.7 LIST SLICING IN PYTHON
List slicing is a powerful feature in Python that allows us to extract a part (or slice) of a list. Slicing enables
us to access a specific range of elements from a list, and it uses a special syntax.
a. Syntax of List Slicing
list[start:end:step]
• start: The index of the first element you want in the slice (inclusive).
• end: The index of the last element you want (exclusive).
• step: The step size or the interval between the elements you want to include (optional).
b. Slicing Behavior
The following table shows the various Slicing behaviour with description and example code.
Operation Description Code Example Output
This retrieves a sublist from a my_list = [10, 20, 30, 40,
50]
Basic Slicing specified start index (inclusive) to [20, 30, 40]
sublist = my_list[1:4]
an end index (exclusive). print(sublist)
If the start and end indices are my_list = [10, 20, 30, 40,
Omitting Start 50] [10, 20, 30,
omitted, the whole list is included sublist = my_list[:] 40, 50]
and End
in the slice. print(sublist)
By using a negative step, you can my_list = [10, 20, 30, 40,
Using a Negative reverse the order of elements, or 50]
[50, 40, 30]
Step select elements moving backward sublist = my_list[4:0:-1]
print(sublist)
in the list.
By providing a step value, you can my_list = [10, 20, 30, 40,
Slicing with a 50]
[10, 30, 50]
extract every nth element from the sublist = my_list[::2]
Step
list (e.g., every second element). print(sublist)
Negative indices start counting my_list = [10, 20, 30, 40,
Slicing with 50]
[20, 30, 40]
from the end of the list, with -1 sublist = my_list[-4:-1]
Negative Indices
being the last element. print(sublist)
A negative step with negative my_list = [10, 20, 30, 40,
Using Negative
indices allows you to reverse the 50] [50, 40, 30,
Step with sublist = my_list[::-1] 20, 10]
list or slice it backward from a
Negative Indices print(sublist)
specific point.
Edge Case:
If you slice an empty list, the result empty_list = [] []
Empty List print(empty_list[:])
will be an empty list.
Slicing
If the start or end index is out of
my_list = [10, 20, 30, 40,
Edge Case: Out- range, Python will handle it 50] []
of-Range Indices gracefully and return an empty list print(my_list[10:])
if needed.
1.8 LIST BUILT-IN FUNCTIONS
Python provides a variety of built-in functions that make it easy to manipulate and work with lists. Below is a
detailed description of the most commonly used list methods. Let's apply all the requested functions to the list
my_list = [42, "Hello", 3.14, True, None, 37, "Hai", 7.98, False] and provide the outputs.
GE3151 Problem Solving and Python Programming 4
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Operation Activity Statement Output
Returns True if all elements False (because of None and
all() all(my_list)
in the list are truthy. False)
Returns True if at least one any(my_list)
True (because of 42, "Hello", True,
any() etc.)
element in the list is truthy.
[42, "Hello", 3.14, True,
Adds an element to the end of my_list.append(100) None, 37, "Hai", 7.98,
append()
the list. False, 100]
Removes all elements from my_list.clear() []
clear()
the list.
[42, "Hello", 3.14, True,
Returns a shallow copy of the new_list =
copy() None, 37, "Hai", 7.98,
list. my_list.copy()
False]
Returns the number of
my_list.count("Hello
count() occurrences of a specified 1
")
element in the list.
["Hello", 3.14, True,
Deletes an element or the del my_list[0] None, 37, "Hai", 7.98,
del
entire list. False]
[(0, 'Hello'), (1, 3.14),
Returns an iterator of index- list(enumerate(my_li (2, True), (3, None), (4,
enumerate() st)) 37), (5, 'Hai'), (6,
value pairs.
7.98), (7, False)]
["Hello", 3.14, True,
Adds elements from an my_list.extend([100,
extend() None, 37, "Hai", 7.98,
iterable to the end of the list. 200])
False, 100, 200]
list(filter(lambda
Filters elements of a list x: isinstance(x, [37, 100, 200] (only integers)
filter()
based on a function. int), my_list))
Returns the index of the first
index() occurrence of a specified my_list.index("Hai") 5
element.
["Hello", 3.14,
Inserts an element at a my_list.insert(2, "Inserted", True, None,
insert() "Inserted") 37, "Hai", 7.98, False,
specified index.
100, 200]
Returns the number of len(my_list) 11
len()
elements in the list.
Converts an iterable into a list((1, 2, 3)) [1, 2, 3]
list()
list.
['Hello', '3.14',
'Inserted', 'True',
Applies a function to each list(map(lambda x:
map() 'None', '37', 'Hai',
item of the list. str(x), my_list))
'7.98', 'False', '100',
'200']
Returns the largest element in max([42, 37, 100,
max() 200
the list. 200])
Returns the smallest element min([42, 37, 100,
min() 37
in the list. 200])
["Hello", 3.14,
Removes and returns an "Inserted", None, 37,
pop() my_list.pop(3)
element at a specified index. "Hai", 7.98, False, 100,
200]
GE3151 Problem Solving and Python Programming 5
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Removes the first occurrence ["Hello", 3.14, None, 37,
my_list.remove("Inse
remove() of a specified element from "Hai", 7.98, False, 100,
rted")
the list. 200]
Returns an iterator that yields [200, 100, False, 7.98,
list(reversed(my_lis
reversed() the elements of the list in 'Hai', 37, None, 3.14,
t))
reverse order. 'Hello']
[200, 100, False, 7.98,
Reverses the elements of the my_list.reverse() 'Hai', 37, None, 3.14,
reverse()
list in place. 'Hello']
[100, 200, 3.14, 37,
Sorts the list in place. The list my_list.sort(key=str
sort() 'Hai', False, 'Hello',
is modified. )
7.98, None]
Returns a new sorted list [100, 200, 3.14, 37,
sorted(my_list,
sorted() without modifying the 'Hai', False, 'Hello',
key=str)
original list. 7.98, None]
Returns the sum of all sum([1, 2, 3, 4, 5]) 15
sum()
numeric elements in the list.
Combines multiple lists into list(zip([1, 2, 3], [(1, 'a'), (2, 'b'), (3,
zip() ["a", "b", "c"])) 'c')]
tuples.
1.9 LIST LOOP IN PYTHON
A List Loop in Python refers to iterating through the elements of a list using a loop, such as a for loop. This
is one of the most common operations when working with lists, allowing you to access each element in the
list sequentially and perform operations on them. There are several ways to loop through a list in Python,
including:
a. Using a for loop
b. Using a while loop
c. Using list comprehensions
1.9.1 Using a for Loop
A for loop is the most straightforward way to iterate through all the elements of a list.
Syntax: for element in list: # Perform operations with element
Example: my_list = [10, 20, 30, 40, 50]
for number in my_list:
print(number)
1.9.2 Using a While Loop
You can also loop through a list using a while loop by manually controlling the index. This method requires
keeping track of the index of the list, and the loop will run as long as the index is within the list’s bounds.
Syntax:
index = 0
while index < len(list):
# Perform operations with list[index]
index += 1
Example:
my_list = [10, 20, 30, 40, 50]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
GE3151 Problem Solving and Python Programming 6
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
1.9.3 USING LIST COMPREHENSIONS
List comprehensions provide a more compact and Pythonic way to iterate through a list and apply operations.
This method is usually used when you want to create a new list by applying an operation to each element of
the original list.
Syntax: new_list = [expression for element in list]
Example:
my_list = [10, 20, 30, 40, 50]
# Using list comprehension to multiply each number by 2
new_list = [number * 2 for number in my_list]
print(new_list)
1.9.4 ADDITIONAL FEATURES OF LIST LOOPS
a. Accessing Index and Element Using enumerate()
If you need both the index and the element during iteration, you can use the enumerate() function, which
returns a tuple of the index and element.
Example:
my_list = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(my_list):
print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Example: Looping Through a List with a for Loop
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Loop through the list
for num in numbers:
# Multiply each number by 2 and print it
print(num * 2)
Example: Looping with enumerate() to Get Both Index and Element
If you need to access both the index and the value of each element in the list, you can use the enumerate()
function.
# List of fruits
fruits = ['apple', 'banana', 'cherry', 'date']
# Loop through the list with index
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Index 3: date
1.9.5 List Mutability in Python
In Python, lists are mutable, meaning that the elements of a list can be changed after the list has been created.
This characteristic distinguishes lists from immutable data types like strings and tuples, where you cannot
modify the elements once they are defined.
GE3151 Problem Solving and Python Programming 7
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
a. Characteristics of Mutability
a) Changing List Elements: You can change the value of an element in a list by directly accessing it
through its index.
b) Adding and Removing Elements: You can append new elements to the list, remove existing elements,
or insert elements at a specific position.
c) Modifying List Length: You can change the size of a list by adding or removing elements.
b. Examples of List Mutability
Operation Description Code Example Output
You can modify an my_list = [10, 20, 30, 40] [10, 20,
a. Changing an my_list[2] = 100 100, 40]
individual element in a
Element in a List print(my_list)
list by using its index.
You can add new my_list = [1, 2, 3] [1, 2, 3,
my_list.append(4) 4]
b. Appending an elements to the end of the print(my_list)
Element list using the append()
method.
You can insert an element my_list = [1, 3, 4] [1, 2, 3,
c. Inserting an Element my_list.insert(1, 2) 4]
at any position in the list
at a Specific Position print(my_list)
using the insert() method.
You can remove an my_list = [10, 20, 100, 30, [10, 20,
40] 30, 40]
d. Removing an element from the list my_list.remove(100)
Element by Value using the remove() print(my_list)
method.
You can remove an my_list = [1, 2, 3, 4, 5] [1, 2, 3,
del my_list[3] 5]
e. Removing an element from the list by print(my_list)
Element by Index specifying its index using
del.
You can modify the size my_list = [1, 2, 3] [1, 2]
f. Changing List my_list.pop()
of the list by adding or
Length print(my_list)
removing elements.
You can modify a list def modify_list(lst): [999, 2,
g. Passing the List to a [Link](200) 3, 4,
inside a function, and it
Function and lst[0] = 999 200]
will affect the original modify_list(my_list)
Modifying it
list. print(my_list)
c. Advantages of List Mutability
• Flexibility: You can easily modify the list after it is created. This makes lists suitable for cases where
you need to perform various operations (like adding, deleting, or modifying elements) on a collection of
data.
• Efficiency: Mutability allows you to modify a list without creating a new one, saving memory and time.
d. Drawback of List Mutability
• Unintentional Changes: Since lists are mutable, unintended changes to a list can occur, especially when
passing lists between functions. If you don't use caution, other parts of your program might accidentally
modify a list, leading to bugs.
• Shared References: Lists passed to functions are shared by reference. If you modify the list inside the
function, it will affect the original list outside the function.
GE3151 Problem Solving and Python Programming 8
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
1.9.6 Aliasing in Lists in Python
Aliasing in Python refers to the situation where two or more variables refer to the same object in memory.
This can happen with mutable objects like lists. When you create a new variable and assign it to an existing
list, both variables end up referring to the same list in memory. This means that changes made through one
variable will affect the other because they both point to the same object.
a. Characteristics of Aliasing
• Same Memory Location: When aliasing occurs, both variables point to the same memory location.
• Changes Affect Both Variables: Since both variables refer to the same object, modifying the object via
one variable will also reflect in the other variable.
• Common with Mutable Objects: Aliasing is especially important with mutable objects like lists,
dictionaries, and sets. Immutable objects like integers and strings don’t exhibit aliasing because they
can’t be changed in place.
b. Example of Aliasing with Lists
# Create a list
original_list = [10, 20, 30]
# Create a new variable that points to the same list (aliasing)
alias_list = original_list
# Modify the list through the alias
alias_list[0] = 100
# Print both lists
print("Original List:", original_list)
print("Alias List:", alias_list)
Output
Original List: [100, 20, 30]
Alias List: [100, 20, 30]
c. Avoiding Aliasing with Copying
If you want to create a new list with the same elements as the original list, but avoid aliasing, you need to
copy the list. Python provides several ways to copy lists:
1. Using the copy() Method (Shallow Copy)
The copy() method creates a new list with the same elements, but it does not copy nested objects inside the
list.
# Create a list
original_list = [10, 20, 30]
# Create a shallow copy of the list
new_list = original_list.copy()
# Modify the new list
new_list[0] = 100
# Print both lists
print("Original List:", original_list)
print("New List:", new_list)
Output:
Original List: [10, 20, 30]
New List: [100, 20, 30]
2. Using Slicing (Shallow Copy)
You can also create a shallow copy of a list using slicing.
# Create a list
original_list = [10, 20, 30]
# Create a shallow copy using slicing
new_list = original_list[:]
GE3151 Problem Solving and Python Programming 9
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Modify the new list
new_list[0] = 100
# Print both lists
print("Original List:", original_list)
print("New List:", new_list)
Output:
Original List: [10, 20, 30]
New List: [100, 20, 30]
3. Using the list() Constructor (Shallow Copy)
The list() constructor can also be used to create a new list that is a copy of the original list.
# Create a list
original_list = [10, 20, 30]
# Create a shallow copy using the list() constructor
new_list = list(original_list)
# Modify the new list
new_list[0] = 100
# Print both lists
print("Original List:", original_list)
print("New List:", new_list)
Output:
Original List: [10, 20, 30]
New List: [100, 20, 30]
4. Deep Copy
If your list contains nested lists or other mutable objects, and you want to avoid aliasing at all levels, you
should use a deep copy. A deep copy creates a new list and also recursively copies all nested objects inside
it. Python provides the copy module for this purpose.
import copy
# Create a list with a nested list
original_list = [10, 20, [30, 40]]
# Create a deep copy
deep_copy_list = [Link](original_list)
# Modify the nested list in the deep copy
deep_copy_list[2][0] = 100
# Print both lists
print("Original List:", original_list)
print("Deep Copy List:", deep_copy_list)
Output:
Original List: [10, 20, [30, 40]]
Deep Copy List: [10, 20, [100, 40]]
1.9.7 Cloning a List in Python
Cloning a list refers to creating a new copy of an existing list, so that the original list and the cloned list are
independent of each other. This is particularly useful when you want to modify the copy without affecting the
original list. In Python, cloning a list is commonly done by creating a new list that contains the same elements
as the original list, but pointing to a different memory location. This avoids the issues caused by aliasing,
where changes to one list would also affect another list.
a. Methods for Cloning a List
1. Using the copy() Method
The copy() method is the most straightforward way to clone a list. It creates a shallow copy of the list,
meaning that it copies the list itself, but not any nested objects.
# Original list
original_list = [10, 20, 30]
GE3151 Problem Solving and Python Programming 10
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Clone the list using the copy() method
cloned_list = original_list.copy()
# Modify the cloned list
cloned_list[0] = 100
# Print both lists
print("Original List:", original_list)
print("Cloned List:", cloned_list)
Output:
Original List: [10, 20, 30]
Cloned List: [100, 20, 30]
2. Using List Slicing
List slicing is another simple way to clone a list. By using the [:] operator, you can create a new list with the
same elements as the original list. Slicing [:] creates a new list with the same elements. The modification to
the cloned list does not affect the original list.
# Original list
original_list = [10, 20, 30]
# Clone the list using slicing
cloned_list = original_list[:]
# Modify the cloned list
cloned_list[1] = 200
# Print both lists
print("Original List:", original_list)
print("Cloned List:", cloned_list)
Output:
Original List: [10, 20, 30]
Cloned List: [10, 200, 30]
3. Using the list() Constructor
You can also clone a list by passing it to the list() constructor, which will create a new list containing the
same elements. This method also creates a new list with the same elements, and modifying the cloned list
will not affect the original list.
# Original list
original_list = [10, 20, 30]
# Clone the list using the list() constructor
cloned_list = list(original_list)
# Modify the cloned list
cloned_list[2] = 300
# Print both lists
print("Original List:", original_list)
print("Cloned List:", cloned_list)
Output:
Original List: [10, 20, 30]
Cloned List: [10, 20, 300]
4. Using the copy Module for Deep Copy (For Nested Lists)
If your list contains nested lists or other mutable objects, and you want to clone the list and its nested objects
(i.e., create a deep copy), you can use the deepcopy() function from the copy module.
import copy
# Original list with a nested list
original_list = [10, 20, [30, 40]]
# Clone the list using deepcopy
cloned_list = [Link](original_list)
# Modify the nested list in the cloned list
cloned_list[2][0] = 100
# Print both lists
GE3151 Problem Solving and Python Programming 11
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
print("Original List:", original_list)
print("Cloned List:", cloned_list)
Output:
Original List: [10, 20, [30, 40]]
Cloned List: [10, 20, [100, 40]]
1.9.8 List Deletion in Python
In Python, you can delete elements from a list using various methods. Deleting elements from a list removes
them from memory, and it can be done in several ways, such as by index, value, or by removing the entire
list.
a. Methods for Deleting List Elements
1. Using del Statement
The del statement is used to remove an element at a specific index from the list or to delete the entire list. It
can also be used to remove a slice of the list.
• Delete an element by index: You can use del to delete an element at a specific index in the list.
• Delete a slice of the list: You can delete multiple elements using slicing.
2. Using remove() Method
The remove() method is used to delete an element by its value. If the element appears multiple times in the
list, only the first occurrence is removed. If the value is not found in the list, it raises a ValueError.
3. Using pop() Method
The pop() method removes an element from a list by index and returns the element that was removed. If no
index is provided, it removes and returns the last element from the list. If the index is out of range, it raises an
IndexError.
4. Using clear() Method
The clear() method removes all the elements from the list, leaving it empty. This is useful when you want
to reset the list without deleting the list object itself.
Summary of List Deletion Methods
Method Description Example Code
del
Removes an element by index or a slice of elements. del my_list[2]or del
Can also be used to delete the entire list. my_list
remove(value)
Removes the first occurrence of the specified value. my_list.remove(30)
Raises ValueError if the value is not found.
pop(index)
Removes and returns the element at the specified index. my_list.pop(1) or
If no index is provided, removes the last element. my_list.pop()
clear() Removes all elements from the list, leaving it empty. my_list.clear()
Example
my_list = [10, 20, 30, 40, 50]
Operation Code Example
1. Using del to delete an element by del my_list[2]
index 2:", my_list)
index
2. Using del to delete a slice of the list del my_list[1:4]
3. Using remove() to delete an my_list = [10, 20, 30, 40, 50]
my_list.remove(30)
element by value
GE3151 Problem Solving and Python Programming 12
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
4. Using pop() to delete and return an my_list = [10, 20, 30, 40, 50]
removed_item = my_list.pop(1)
element by index
5. Using pop() without an index to my_list = [10, 20, 30, 40, 50]
removed_item = my_list.pop()
delete the last element
6. Using clear() to remove all my_list = [10, 20, 30, 40, 50]
my_list.clear()
elements
my_list = [10, 20, 30, 40, 50]
7. Using del to delete the entire list del my_list
1.10 LIST PARAMETERS IN PYTHON
In Python, lists can be passed as parameters to functions. This allows you to manipulate or perform operations
on lists within a function. Lists are mutable objects in Python, meaning changes to the list inside the function
will affect the original list outside the function, unless the list is explicitly copied.
a. Types of List Parameters
1. Passing a list as a parameter You can pass a list directly to a function as an argument, and the function
can then modify the original list (since lists are mutable).
2. Returning a list from a function Functions can return lists as output, allowing you to generate and
return lists dynamically.
3. List as Default Parameters A function can have a list as a default parameter, but be cautious as mutable
default parameters can lead to unexpected behavior.
Examples
1. Passing a List as a Parameter
You can pass a list to a function, and the function can modify the list directly.
# Function that modifies a list by appending an element
def add_to_list(my_list, value):
my_list.append(value)
print("Inside the function:", my_list)
# Calling the function
my_list = [1, 2, 3]
add_to_list(my_list, 4)
# Print the list outside the function
print("Outside the function:", my_list)
Output:
Inside the function: [1, 2, 3, 4]
Outside the function: [1, 2, 3, 4]
2. Returning a List from a Function
A function can return a list after performing some operation on it.
# Function that returns a new list with squares of the original list
def square_elements(my_list):
return [x ** 2 for x in my_list]
# Calling the function
original_list = [1, 2, 3, 4]
squared_list = square_elements(original_list)
# Print both lists
print("Original List:", original_list)
print("Squared List:", squared_list)
Output:
Original List: [1, 2, 3, 4]
Squared List: [1, 4, 9, 16]
GE3151 Problem Solving and Python Programming 13
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
3. List as a Default Parameter
You can set a list as a default parameter in a function. However, be cautious when using mutable types (like
lists) as default arguments, because the same list object is used across multiple calls to the function.
# Function with a list as a default parameter
def add_value_to_list(value, my_list=None):
if my_list is None:
my_list = [] # Initialize a new list if no list is provided
my_list.append(value)
return my_list
# Calling the function without passing a list
list1 = add_value_to_list(10)
list2 = add_value_to_list(20)
print("List 1:", list1)
print("List 2:", list2)
Output:
List 1: [10]
List 2: [20]
4. Modifying the Original List Inside a Function
Since lists are mutable, changes made to the list inside a function will affect the original list outside the
function unless you create a copy of the list.
def remove_first_element(my_list):
if my_list:
my_list.pop(0) # Remove the first element
# Original list
my_list = [10, 20, 30, 40]
remove_first_element(my_list)
# Print the modified list
print("Modified List:", my_list)
Output:
Modified List: [20, 30, 40]
1.11 ADVANCED LIST PROCESSING IN PYTHON
Python provides various ways to process and manipulate lists efficiently. Advanced list processing techniques
allow you to handle large datasets and perform complex operations with ease. These techniques include list
comprehensions, map(), filter(), reduce(), zip(), and others. Below are some advanced list processing
techniques with examples:
1. List Comprehensions
List comprehensions provide a concise way to create lists. They are often more readable and faster than
traditional for loops.
Syntax: [expression for item in iterable if condition]
Example:
# Create a list of squares of even numbers
numbers = [1, 2, 3, 4, 5, 6]
squares = [x**2 for x in numbers if x % 2 == 0]
print(squares) # Output: [4, 16, 36]
2. map() Function
The map() function applies a given function to all items in an input list (or any iterable) and returns a map
object (an iterator).
Syntax: map(function, iterable)
GE3151 Problem Solving and Python Programming 14
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Example:
# Using map to square each number in the list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
3. filter() Function
The filter() function filters out elements from an iterable based on a given condition. It returns an iterator
containing only the elements for which the function returns True.
Syntax: filter(function, iterable)
Example:
# Using filter to get only even numbers from the list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
4. reduce() Function (from functools module)
The reduce() function from the functools module applies a binary function (a function that takes two
arguments) cumulatively to the items in an iterable, from left to right, so as to reduce the iterable to a single
value.
Syntax: from functools import reduce
reduce(function, iterable)
Example:
from functools import reduce
# Using reduce to get the product of all numbers in the list
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
5. zip() Function
The zip() function combines multiple iterables into a single iterable, where each item is a tuple containing
elements from all input iterables. It’s commonly used to pair elements from two lists.
Syntax: zip(iterable1, iterable2, ...)
Example:
# Using zip to combine two lists into pairs
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 30, 18]
zipped = list(zip(names, ages))
print(zipped) # Output: [('Alice', 24), ('Bob', 30), ('Charlie', 18)]
6. Nested List Comprehensions
List comprehensions can be nested inside each other to process multi-dimensional lists (e.g., matrices or lists
of lists).
Syntax: [[expression for item in sublist] for sublist in iterable]
Example:
# Flattening a 2D list using a nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in matrix for item in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
GE3151 Problem Solving and Python Programming 15
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
7. List Slicing with Step
List slicing is a powerful way to extract portions of a list, and it can also include steps to select items at
regular intervals.
Syntax: list[start:end:step]
Example:
# Getting every second element from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sliced = numbers[::2]
print(sliced) # Output: [1, 3, 5, 7, 9]
8. List Unpacking
List unpacking allows you to assign elements of a list directly to multiple variables.
Syntax: a, b, c = list
Example:
# Unpacking a list into variables
numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c) # Output: 1 2 3
9. Using any() and all() with Lists
• any() checks if any element in the list is True.
• all() checks if all elements in the list are True.
Syntax: any(iterable)
all(iterable)
Example:
# Using any() to check if any element is greater than 5
numbers = [1, 2, 3, 6]
print(any(x > 5 for x in numbers)) # Output: True
# Using all() to check if all elements are positive
print(all(x > 0 for x in numbers)) # Output: True
10. List Sorting with sorted() and sort()
• sorted() returns a new sorted list from the elements of any iterable.
• sort() sorts the list in-place and modifies the original list.
Syntax:
sorted(list) # Returns a new sorted list
[Link]() # Sorts the list in-place
Example:
# Using sorted to sort a list in descending order
numbers = [4, 1, 3, 9, 7]
sorted_list = sorted(numbers, reverse=True)
print(sorted_list) # Output: [9, 7, 4, 3, 1]
# Using sort to sort the original list in ascending order
[Link]()
print(numbers) # Output: [1, 3, 4, 7, 9]
1.12 LIST COMPREHENSION IN PYTHON
List comprehension is a concise and powerful way to create lists in Python. It allows you to generate a new
list by applying an expression to each item in an iterable (such as a list, tuple, or range). It provides a more
syntactically elegant and often more efficient alternative to using loops for creating lists.
Basic Syntax of List Comprehension
GE3151 Problem Solving and Python Programming 16
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
[expression for item in iterable if condition]
• expression: The expression or operation to apply to each item in the iterable.
• item: Each element from the iterable that is being processed.
• iterable: A collection (list, range, etc.) to loop over.
• condition (optional): A condition to filter elements. Only elements that satisfy the condition will be
included in the new list.
Basic Example
# Create a list of squares of numbers
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
Using Conditional Statements in List Comprehension
List comprehensions can include an if condition to filter elements from the iterable.
Example:
# Create a list of squares of even numbers only
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36]
Using else in List Comprehension
You can also use an else clause along with if to apply an expression based on a condition.
Example:
# Create a list of 'Even' or 'Odd' based on the number's parity
numbers = [1, 2, 3, 4, 5]
parity = ['Even' if x % 2 == 0 else 'Odd' for x in numbers]
print(parity) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
Nested List Comprehension
You can nest list comprehensions within each other to process multi-dimensional data, such as matrices or
lists of lists.
Example:
# Flatten a 2D list using list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in matrix for item in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List Comprehension with Multiple Iterables
You can also use multiple iterables in a list comprehension to create combinations of elements.
Example:
# Pair elements from two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 30, 18]
pairs = [(name, age) for name, age in zip(names, ages)]
print(pairs) # Output: [('Alice', 24), ('Bob', 30), ('Charlie', 18)]
Performance Considerations
GE3151 Problem Solving and Python Programming 17
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
List comprehensions are generally more efficient than using a for loop to create a new list. This is because
list comprehensions are optimized for this specific task and are executed faster in many cases.
For Loop Example:
# Using a for loop to create a list of squares
numbers = [1, 2, 3, 4, 5]
squares = []
for x in numbers:
[Link](x**2)
print(squares) # Output: [1, 4, 9, 16, 25]
List Comprehension Example:
# Using list comprehension to create a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
2. TUPLES IN PYTHON
2.1 INTRODUCTION
In Python, a tuple is a collection of ordered, immutable, and possibly heterogeneous elements. Unlike lists,
tuples cannot be modified after creation, which means that once a tuple is created, you cannot change its
elements, add new elements, or remove elements. Tuples are defined using parentheses () rather than square
brackets [] (used for lists).
2.2 CHARACTERISTICS OF TUPLES
• Ordered: The elements in a tuple have a defined order, and the order in which they are inserted is
preserved.
• Immutable: Once a tuple is created, its elements cannot be modified (i.e., you cannot change the value
of an element, add new elements, or delete elements).
• Heterogeneous: Tuples can contain elements of different data types, including integers, strings, and
even other tuples.
• Indexable and Iterable: Tuples can be accessed using indexing and can be iterated through using loops
(e.g., for loops).
• Hashable: Since tuples are immutable, they can be used as keys in dictionaries, unlike lists.
2.3 TUPLE SYNTAX
A tuple is created by enclosing elements in parentheses ().
# Example of a tuple
my_tuple = (1, 2, 3, 'a', 'b', 3.14)
You can also create a tuple with just one element by including a trailing comma:
# Single element tuple
single_element_tuple = (10,) # The comma is necessary
2.4 ADVANTAGES OF TUPLES
a. Immutability: Since tuples are immutable, they are more memory-efficient and can be used as
dictionary keys (unlike lists).
b. Performance: Operations on tuples are generally faster than on lists because they are immutable.
GE3151 Problem Solving and Python Programming 18
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
c. Safer: Since the data cannot be modified accidentally, tuples can be used to represent fixed collections
of data.
2.5 DISADVANTAGES OF TUPLES
a. Inflexibility: Since tuples are immutable, you cannot modify them once created. This can be a
disadvantage if you need to perform frequent updates to the collection.
b. Lack of methods: Tuples support only two methods, whereas lists have more built-in methods.
2.6 OPERATIONS ON TUPLES
Tuples are immutable data structures in Python that support various operations. These operations allow you
to manipulate and interact with tuple data without modifying the original tuple. The following table details
the key operations on tuples.
Operation Description Example Output
Concatenation (1, 2) + (3, 4) (1, 2, 3, 4)
Combines two tuples into a new one.
(+)
Repeats a tuple a specified number of (1, 2, 1, 2,
Repetition (*) (1, 2) * 3
times. 1, 2)
Membership 2 in (1, 2, 3) True
Checks if an element exists in the tuple.
(in)
Accesses an element by its position t = (10, 20); t[0] 10
Indexing
(supports negative indexing).
Retrieves a subset of the tuple using start, t = (10, 20, 30);
Slicing (10, 20)
stop, and step. t[0:2]
for x in (1, 2):
Iteration Loops through each element in the tuple. 1 \n 2
print(x)
len()
Returns the number of elements in the len((1, 2, 3)) 3
tuple.
max() Returns the largest element in the tuple. max((1, 2, 3)) 3
min() Returns the smallest element in the tuple. min((1, 2, 3)) 1
sum()
Returns the sum of all numeric elements sum((1, 2, 3)) 6
in the tuple.
tuple() Converts an iterable into a tuple. tuple([1, 2, 3]) (1, 2, 3)
Unpacking Assigns tuple elements to variables. a, b = (1, 2) a = 1, b = 2
count(value)
Returns the number of occurrences of a (1, 2, 2).count(2) 2
value in the tuple.
index(value)
Returns the first index of a specified value (1, 2, 3).index(2) 1
in the tuple.
2.7 SLICING AND INDEXING IN TUPLES
Slicing and indexing are operations used to access and extract elements from tuples based on their position.
Tuples, being ordered collections, allow precise retrieval of data using these methods.
• Indexing: Access individual elements based on position.
• Slicing: Retrieve multiple elements as a new tuple using a range of indices.
Key Differences: Indexing vs. Slicing
Aspect Indexing Slicing
Purpose Access a single element. Access a subset of the tuple.
Result Returns a single value. Returns a new tuple.
GE3151 Problem Solving and Python Programming 19
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Syntax tuple[index] tuple[start:stop:step]
Out-of-Range Raises an IndexError. Returns an empty tuple or adjusts.
Negative Values Retrieves elements from the end. Defines ranges from the end.
a. Indexing
Indexing is used to access individual elements in a tuple by their position. Python supports zero-based
indexing (starting from 0) and negative indexing (starting from -1 for the last element).
Characteristics of Indexing:
• Positive indices count from the left (starting at 0).
• Negative indices count from the right (starting at -1).
Examples:
t = (10, 20, 30, 40)
# Positive Indexing
print(t[0]) # Output: 10 (first element)
print(t[2]) # Output: 30 (third element)
# Negative Indexing
print(t[-1]) # Output: 40 (last element)
print(t[-3]) # Output: 20 (third-to-last element)
Error Handling:
print(t[5]) # Raises IndexError: tuple index out of range
b. Slicing
Slicing is used to extract a portion (or subset) of a tuple by specifying a range of indices. The slice is defined
using the syntax tuple[start:stop:step].
Syntax Components:
• start: The index at which the slice begins (inclusive). Defaults to 0 if omitted.
• stop: The index at which the slice ends (exclusive). Defaults to the length of the tuple if omitted.
• step: The interval between elements in the slice. Defaults to 1 if omitted.
Examples:
t = (10, 20, 30, 40, 50)
# Basic Slicing
print(t[1:4]) # Output: (20, 30, 40) (from index 1 to 3)
print(t[:3]) # Output: (10, 20, 30) (from the start to index 2)
print(t[2:]) # Output: (30, 40, 50) (from index 2 to the end)
# Slicing with Step
print(t[::2]) # Output: (10, 30, 50) (every second element)
print(t[::-1]) # Output: (50, 40, 30, 20, 10) (reversed tuple)
# Negative Slicing
print(t[-4:-1]) # Output: (20, 30, 40) (subset using negative indices)
Error Handling:
• Slicing never raises an IndexError. If the indices are out of bounds, it returns an empty tuple or
adjusts to valid indices.
2.8 DELETING AND UPDATING TUPLES IN PYTHON
Tuples are immutable, meaning their contents cannot be altered once created. However, you can delete an
entire tuple or create modified versions of a tuple to simulate updates. Here's an explanation of how deletion
and updating work with tuples:
GE3151 Problem Solving and Python Programming 20
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
1. Deleting Tuples
While you cannot delete specific elements from a tuple due to immutability, you can delete the entire tuple
using the del statement.
a. Deleting an Entire Tuple
You can use the del keyword to remove the tuple object from memory. After deletion, attempting to access
the tuple will result in a NameError.
Example:
t = (10, 20, 30)
del t # Deletes the tuple
# print(t) # Raises NameError: name 't' is not defined
b. Attempting to Delete Individual Elements
Tuples do not support item deletion. Trying to delete specific elements raises a TypeError.
Example:
t = (10, 20, 30)
del t[1] # Raises TypeError: 'tuple' object doesn't support item deletion
2. Updating Tuples
Tuples are immutable, so their elements cannot be directly modified. However, you can create new tuples
that incorporate the desired changes.
a. Adding Elements
To "add" elements to a tuple, you can concatenate it with another tuple. This creates a new tuple that
includes the additional elements.
Example:
t = (10, 20, 30)
t = t + (40, 50)
print(t) # Output: (10, 20, 30, 40, 50)
b. Removing Elements
To "remove" elements, you can slice the tuple to exclude the unwanted elements and concatenate the
remaining parts into a new tuple.
Example:
t = (10, 20, 30, 40)
# Remove the element 20
t = t[:1] + t[2:]
print(t) # Output: (10, 30, 40)
c. Modifying Elements
Although tuple elements cannot be directly modified, you can convert the tuple into a list (which is
mutable), perform the modifications, and then convert it back into a tuple.
Example:
t = (10, 20, 30)
# Change the second element (20) to 25
lst = list(t)
lst[1] = 25
t = tuple(lst)
print(t) # Output: (10, 25, 30)
3. Why Tuples Are Immutable
GE3151 Problem Solving and Python Programming 21
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
• Fixed Data: Tuples are often used for fixed collections of data, such as coordinates or constant
values, where immutability prevents accidental modifications.
• Hashability: Tuples are hashable if they contain only hashable elements, making them usable as
keys in dictionaries.
Summary
Operation Directly Supported Workaround
Delete an entire tuple Yes (del tuple) -
Delete specific elements No Use slicing or filtering to create a new tuple.
Add elements No Concatenate with another tuple to create a new one.
Modify elements No Convert to a list, modify, and convert back to a tuple.
2.9 TUPLE FUNCTIONS
Tuple functions are built-in methods in Python that allow you to perform various operations on tuples. Since
tuples are immutable (i.e., their elements cannot be changed after creation), the functions related to tuples
generally help you access, count, search, or convert data rather than modify it directly. These functions can be
used to tetrieve information about a tuple (such as length, maximum, minimum, etc.) Search for elements or
count occurrences and to convert other data types (like lists) into tuples.
1. len(): Measures the size of the tuple.
2. max(): Finds the maximum value among tuple elements. All elements must be comparable (e.g., all
integers).
3. min(): Finds the minimum value among tuple elements.
4. sum(): Adds up all the numeric values in a tuple.
5. tuple(): Converts an iterable such as a list or string into a tuple.
6. index(value): Identifies the position of the first occurrence of a specific value in the tuple.
7. count(value): Counts how often a specific value occurs in the tuple.
Function/Method Description Example Output
len() Returns the number of elements in the tuple. t = (1, 2, 3); len(t) 3
max() Returns the largest element in the tuple. t = (1, 2, 3); max(t) 3
min() Returns the smallest element in the tuple. t = (1, 2, 3); min(t) 1
sum()
Returns the sum of all elements in the tuple t = (1, 2, 3); sum(t) 6
(only numeric elements).
Converts an iterable (e.g., list, string) into a (1, 2,
tuple() tuple([1, 2, 3])
tuple. 3)
Returns the first index of the specified t = (10, 20, 30);
index(value) 1
value. Raises ValueError if not found. [Link](20)
Returns the number of times the specified t = (10, 20, 20, 30);
count(value) 2
value appears in the tuple. [Link](20)
2.10 TUPLE ASSIGNMENT
Tuple assignment in Python allows you to assign multiple values to variables in a single statement. The key
feature of tuple assignment is that it supports unpacking, which means you can assign values from a tuple (or
other iterable) to multiple variables in a single line of code.
Basic Tuple Assignment
GE3151 Problem Solving and Python Programming 22
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Tuple assignment works by matching the number of elements in the tuple with the number of variables on the
left-hand side of the assignment. The values in the tuple are unpacked and assigned to the corresponding
variables.
Examples of Tuple Assignment
1. Basic Assignment
In the simplest form, you can assign each element of a tuple to a corresponding variable.
# Tuple with 3 elements
t = (10, 20, 30)
# Tuple assignment
a, b, c = t
print(a) # Output: 10
print(b) # Output: 20
print(c) # Output: 30
In this example, the tuple t is unpacked into three variables: a, b, and c. The value 10 goes to a, 20 goes to
b, and 30 goes to c.
2. Tuple Assignment with Different Lengths
The number of variables on the left-hand side must match the number of elements in the tuple, otherwise, a
ValueError will be raised.
# Tuple with 3 elements
t = (1, 2, 3)
# Correct assignment
a, b, c = t # This works because there are exactly 3 elements
# Incorrect assignment (ValueError)
# a, b = t # This will raise ValueError: not enough values to unpack (expected
2, got 3)
3. Swapping Values
One common use of tuple assignment is to swap the values of two variables without needing a temporary
third variable. This is a feature unique to Python and is made easy with tuple assignment.
x = 5
y = 10
# Swap values
x, y = y, x
print(x) # Output: 10
print(y) # Output: 5
Here, Python automatically unpacks the tuple (y, x) and assigns y to x and x to y, effectively swapping
their values.
4. Ignoring Elements with _
If you want to unpack a tuple but don't care about some of the values, you can use the underscore (_) to
ignore specific elements.
t = (1, 2, 3, 4)
# Ignore the last two elements
a, b, _, _ = t
print(a) # Output: 1
print(b) # Output: 2
In this case, the values 3 and 4 are ignored, and only the first two elements are assigned to a and b.
GE3151 Problem Solving and Python Programming 23
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
5. Nested Tuple Assignment
You can also unpack nested tuples, where each nested tuple is unpacked in a similar way.
t = ((1, 2), (3, 4))
# Nested tuple assignment
(a, b), (c, d) = t
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
print(d) # Output: 4
Here, the outer tuple contains two inner tuples, and each inner tuple is unpacked into individual variables.
6. Tuple Assignment with * (Extended Unpacking)
In Python 3, you can also use the * operator to collect excess values in a tuple when unpacking. This is
called extended unpacking.
Example of Extended Unpacking:
t = (1, 2, 3, 4, 5)
# Collect remaining values in the variable 'others'
a, b, *others = t
print(a) # Output: 1
print(b) # Output: 2
print(others) # Output: [3, 4, 5]
In this example, a gets 1, b gets 2, and the rest of the tuple (3, 4, 5) is collected into the others list.
Example with Split Assignment:
t = (1, 2, 3, 4, 5)
# Assign the first and last elements, and collect the middle ones
first, *middle, last = t
print(first) # Output: 1
print(middle) # Output: [2, 3, 4]
print(last) # Output: 5
Here, the *middle collects all the elements between the first and last, and first and last hold the first and
last elements, respectively.
2.11 TUPLE AS RETURN VALUE
1. Tuple as Return Value in Python
In Python, a tuple can be returned from a function just like any other data type (such as a list, string, or
integer). When a function returns a tuple, it can be used to return multiple values in a single statement,
making it convenient for functions that need to return more than one value.
2. Why Use a Tuple as a Return Value?
a. Multiple Values: A tuple allows you to return multiple values from a function without needing to use a
more complex data structure.
b. Immutable Data: Tuples are immutable, so the values returned in a tuple cannot be modified, ensuring
the integrity of the data.
c. Readable: Returning a tuple can be clearer and more concise compared to returning a list or using global
variables.
GE3151 Problem Solving and Python Programming 24
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
3. Examples of Using Tuples as Return Values
a. Returning Multiple Values
A function can return a tuple containing multiple values. For instance, if you want to return both the quotient
and the remainder of a division operation:
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder # Returning as a tuple
# Call the function
result = divide(10, 3)
# Print the result
print(result) # Output: (3, 1)
b. Unpacking the Tuple
You can unpack the tuple returned from a function directly into multiple variables.
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
# Unpack the returned tuple into separate variables
q, r = divide(10, 3)
print("Quotient:", q) # Output: Quotient: 3
print("Remainder:", r) # Output: Remainder: 1
c. Returning a Tuple with Different Data Types
Tuples can hold different data types, and you can return a tuple containing mixed types.
def get_person_info(name, age):
return name, age # Return a tuple of string and integer
# Call the function
info = get_person_info("John", 30)
# Print the result
print(info) # Output: ('John', 30)
4. Returning a Tuple from Multiple Function Calls
You can also combine tuples from multiple function calls by returning a tuple from each and combining
them.
def get_coordinates():
return (10, 20)
def get_velocity():
return (5, 15)
# Combine the tuples returned from both functions
coordinates = get_coordinates()
velocity = get_velocity()
# Combine them into one tuple
result = coordinates + velocity
print(result) # Output: (10, 20, 5, 15)
5. Returning a Tuple for Function Status and Result
Sometimes, a function might need to return both a status and a result, and tuples are ideal for this:
def calculate_square(number):
if number < 0:
GE3151 Problem Solving and Python Programming 25
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
return False, "Negative numbers are not allowed"
else:
return True, number ** 2
# Call the function
status, result = calculate_square(5)
print(status) # Output: True
print(result) # Output: 25
Summary of Returning Tuples
• Multiple Values: You can return more than one value from a function using a tuple.
• Unpacking: The returned tuple can be unpacked into multiple variables.
• Different Data Types: Tuples can contain elements of different data types.
• Combining Results: Multiple tuples returned from different functions can be combined.
• Status and Results: Tuples are useful when returning both status and result from a function.
3. PYTHON DICTIONARY
A dictionary in Python is an unordered, mutable collection of key-value pairs. Each key is unique, and it is
associated with a value. Dictionaries are used to store data in a way that allows fast lookups, modifications,
and retrieval of values based on keys. In Python, dictionaries are implemented using the dict data type.
3.1 CHARACTERISTICS OF PYTHON DICTIONARIES
• Unordered: Dictionaries are unordered collections. The order of the key-value pairs is not guaranteed to
be preserved (although in Python 3.7+ insertion order is preserved, this should not be relied upon in all
situations).
• Mutable: You can change, add, or remove key-value pairs in a dictionary after it is created.
• Key-Value Pairs: Each item in a dictionary is a pair consisting of a key and a value. Keys are used to
access the associated values.
• Unique Keys: In a dictionary, each key must be unique. If you assign a new value to an existing key, the
previous value will be overwritten.
• Heterogeneous: Keys and values in a dictionary can be of any data type. The keys, however, must be
immutable (e.g., strings, numbers, or tuples), while the values can be of any type, including lists or other
dictionaries.
3.2 SYNTAX OF PYTHON DICTIONARY
The basic syntax for creating a dictionary is:
dictionary_name = {key1: value1, key2: value2, key3: value3, ...}
Example:
# Create a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
# Access a value by key
print(person["name"]) # Output: Alice
# Add a new key-value pair
person["job"] = "Engineer"
# Update an existing key-value pair
person["age"] = 31
# Remove a key-value pair
del person["city"]
# Check the updated dictionary
print(person) # Output: {'name': 'Alice', 'age': 31, 'job': 'Engineer'}
GE3151 Problem Solving and Python Programming 26
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
3.3 DICTIONARY METHODS
• dict[key]: Access a value by key.
• dict[key] = value: Add or update a key-value pair.
• del dict[key]: Remove a key-value pair.
• [Link](key): Return the value for the key, or None if the key doesn’t exist.
• [Link](): Return a list of all keys in the dictionary.
• [Link](): Return a list of all values in the dictionary.
• [Link](): Return a list of all key-value pairs (tuples) in the dictionary.
Example Using Methods:
# Create a dictionary
student = {"name": "John", "age": 20, "course": "Mathematics"}
# Access value using get method
print([Link]("name")) # Output: John
# Get all keys
print([Link]()) # Output: dict_keys(['name', 'age', 'course'])
# Get all values
print([Link]()) # Output: dict_values(['John', 20, 'Mathematics'])
# Get all key-value pairs
print([Link]()) # Output: dict_items([('name', 'John'), ('age', 20),
('course', 'Mathematics')])
3.4 CREATION AND ACCESSING DICTIONARIES IN PYTHON
a. Creating Dictionaries
A dictionary in Python is created using curly braces {} or the built-in dict() function. The syntax for a
dictionary involves key-value pairs, where each key is separated from its corresponding value by a colon (:),
and the key-value pairs are separated by commas.
1. Using Curly Braces {}
# Creating a dictionary with curly braces
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
2. Using the dict() Function You can also create a dictionary using the dict() constructor, where key-value
pairs are passed as keyword arguments.
# Creating a dictionary using the dict() constructor
my_dict = dict(name="Alice", age=25, city="New York")
3. Creating an Empty Dictionary You can create an empty dictionary using either {} or the dict()
constructor.
empty_dict = {} # Empty dictionary using {}
another_empty_dict = dict() # Empty dictionary using dict()
4. Using a List of Tuples You can create a dictionary from a list of tuples, where each tuple contains a
key-value pair.
my_dict = dict([("name", "Alice"), ("age", 25), ("city", "New York")])
5. Using Dictionary Comprehensions You can create dictionaries using a dictionary comprehension,
which is useful when creating a dictionary from an existing list or range.
my_dict = {x: x**2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
b. Accessing Values in a Dictionary
There are several ways to access the values stored in a dictionary:
GE3151 Problem Solving and Python Programming 27
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
1. Using the Key Directly You can access a value by referring to its key inside square brackets []. If the
key does not exist, a KeyError is raised.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Access value by key
print(my_dict["name"]) # Output: Alice
print(my_dict["age"]) # Output: 25
2. Using the get() Method The get() method allows you to access a value by its key, but it does not
raise an error if the key is not found. Instead, it returns None (or a specified default value).
# Access value using get() method
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("job")) # Output: None (since "job" key doesn't exist)
# Providing a default value if the key doesn't exist
print(my_dict.get("job", "Not Available")) # Output: Not Available
3. Using the keys() Method The keys() method returns a view object that displays a list of all the keys
in the dictionary.
# Get all keys in the dictionary
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'age', 'city'])
4. Using the values() Method The values() method returns a view object that displays a list of all the
values in the dictionary.
# Get all values in the dictionary
values = my_dict.values()
print(values) # Output: dict_values(['Alice', 25, 'New York'])
5. Using the items() Method The items() method returns a view object that displays a list of tuples,
where each tuple is a key-value pair.
# Get all key-value pairs as tuples
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New
York')])
6. Using the pop() Method The pop() method removes and returns a value associated with a specific key.
If the key does not exist, it raises a KeyError. You can also specify a default value to return if the key is
not found.
# Remove and return a value using pop()
removed_value = my_dict.pop("age")
print(removed_value) # Output: 25
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
7. Using the popitem() Method The popitem() method removes and returns an arbitrary (key, value)
pair from the dictionary. In Python 3.7+, it returns the last inserted key-value pair.
# Remove and return an arbitrary key-value pair
removed_item = my_dict.popitem()
print(removed_item) # Output: ('city', 'New York')
print(my_dict) # Output: {'name': 'Alice'}
Examples of Dictionary Creation and Access
Example 1: Creating a Dictionary and Accessing Values
# Create a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
# Access values using the key
GE3151 Problem Solving and Python Programming 28
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
print(person["name"]) # Output: Alice
print([Link]("age")) # Output: 30
Example 2: Using get() Method and Default Value
person = {"name": "Alice", "age": 30}
# Access key with get(), returning default if not found
print([Link]("city", "Unknown")) # Output: Unknown
Example 3: Using keys(), values(), and items()
person = {"name": "Alice", "age": 30, "city": "New York"}
# Get all keys
print([Link]()) # Output: dict_keys(['name', 'age', 'city'])
# Get all values
print([Link]()) # Output: dict_values(['Alice', 30, 'New York'])
# Get all key-value pairs
print([Link]()) # Output: dict_items([('name', 'Alice'), ('age', 30),
('city', 'New York')])
Example 4: Using pop() and popitem()
person = {"name": "Alice", "age": 30, "city": "New York"}
# Using pop() to remove a specific key-value pair
age = [Link]("age")
print(age) # Output: 30
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
# Using popitem() to remove an arbitrary key-value pair
item = [Link]()
print(item) # Output: ('city', 'New York')
print(person) # Output: {'name': 'Alice'}
3.5 DELETION OF ELEMENTS FROM DICTIONARIES IN PYTHON
In Python, dictionaries are mutable, meaning you can modify them by adding, updating, or deleting key-value
pairs. When you want to remove items from a dictionary, Python provides several methods and techniques to
do so. Below are the common ways to delete elements from dictionaries:
Methods for Deleting Elements from Dictionaries
1. Using the del Statement The del statement is used to remove a specific key-value pair from a
dictionary. It removes the item entirely and will raise a KeyError if the key does not exist.
Syntax: del dictionary[key]
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Deleting a key-value pair using del
del my_dict["age"]
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
# Attempting to delete a non-existent key
del my_dict["job"] # Raises KeyError: 'job'
2. Using the pop() Method The pop() method is used to remove a key-value pair and return the value
associated with the key. If the key is not found, a KeyError is raised, unless a default value is provided.
Syntax: value = [Link](key, default)
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
GE3151 Problem Solving and Python Programming 29
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Remove and return the value for the key "age"
age = my_dict.pop("age")
print(age) # Output: 25
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
my_dict = {"name": "Alice", "age": 25}
# Attempt to pop a non-existent key with a default value
job = my_dict.pop("job", "Not Available")
print(job) # Output: Not Available
3. Using the popitem() Method The popitem() method removes and returns an arbitrary (key, value)
pair from the dictionary. In Python 3.7+, it removes the last inserted key-value pair. If the dictionary is
empty, calling popitem() will raise a KeyError.
Syntax: key, value = [Link]()
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Remove and return an arbitrary key-value pair
key, value = my_dict.popitem()
print(f"Removed: {key} = {value}") # Output: Removed: city = New York
print(my_dict) # Output: {'name': 'Alice', 'age': 25}
4. Using the clear() Method The clear() method removes all key-value pairs from the dictionary,
making it empty. It does not raise any errors if the dictionary is already empty.
Syntax: [Link]()
Example: my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Remove all elements
my_dict.clear()
print(my_dict) # Output: {}
Example of Deleting Elements from a Dictionary
# Create a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Deleting a specific key using del
del my_dict["age"]
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
# Remove a key and get the value using pop()
city = my_dict.pop("city")
print(city) # Output: New York
print(my_dict) # Output: {'name': 'Alice'}
# Remove an arbitrary key-value pair using popitem()
key, value = my_dict.popitem()
print(f"Removed: {key} = {value}") # Output: Removed: name = Alice
print(my_dict) # Output: {}
# Clear all elements from the dictionary
my_dict.clear()
print(my_dict) # Output: {}
GE3151 Problem Solving and Python Programming 30
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
3.6 UPDATING THE ELEMENTS OF A DICTIONARY IN PYTHON
In Python, dictionaries are mutable, meaning that their elements can be modified after the dictionary is
created. Updating a dictionary involves adding new key-value pairs, modifying existing pairs, or removing
and replacing values. There are several ways to update elements in a dictionary.
1.
2. Methods to Update Elements in a Dictionary
a. Using the Assignment Operator (=)
You can update an existing key-value pair by assigning a new value to a key. If the key does not exist, a new
key-value pair will be added.
Syntax: dictionary[key] = new_value
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Update the value of an existing key
my_dict["age"] = 26
# Add a new key-value pair if the key doesn't exist
my_dict["job"] = "Engineer"
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job':
'Engineer'}
b. Using the update() Method
The update() method is used to update multiple key-value pairs in a dictionary. You can provide another
dictionary, or a list of tuples, or keyword arguments as arguments.
Syntax: [Link](other_dictionary) # From another dictionary
[Link](key1=value1, key2=value2, ...) # Using keyword arguments
Example 1: Updating with Another Dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Update using another dictionary
my_dict.update({"age": 26, "city": "Los Angeles", "job": "Engineer"})
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'Los Angeles',
'job': 'Engineer'}
Example 2: Updating with Keyword Arguments
my_dict = {"name": "Alice", "age": 25}
# Update using keyword arguments
my_dict.update(age=26, city="New York", job="Engineer")
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job':
'Engineer'}
c. Using Dictionary Comprehensions
You can also use dictionary comprehensions to create a new dictionary or update the existing one based on
some condition or transformation.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
# Increase the value of each key by 1
my_dict = {key: value + 1 for key, value in my_dict.items()}
print(my_dict) # Output: {'a': 2, 'b': 3, 'c': 4}
d. Updating a Nested Dictionary
In Python, dictionaries can also contain other dictionaries (nested dictionaries). You can update elements in
nested dictionaries by referencing the inner dictionary's key.
GE3151 Problem Solving and Python Programming 31
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Example:
my_dict = {
"name": "Alice",
"contact": {"email": "alice@[Link]", "phone": "123-456-7890"}}
# Update a value inside the nested dictionary
my_dict["contact"]["email"] = "alice@[Link]"
# Add a new key-value pair inside the nested dictionary
my_dict["contact"]["address"] = "123 Main St"
print(my_dict)
# Output: {'name': 'Alice', 'contact': {'email': 'alice@[Link]', 'phone':
'123-456-7890', 'address': '123 Main St'}}
Examples of Dictionary Updates
Example 1: Using Assignment (=)
my_dict = {"name": "Alice", "age": 25}
# Update the value of an existing key
my_dict["age"] = 26
# Add a new key-value pair
my_dict["job"] = "Engineer"
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'job': 'Engineer'}
Example 2: Using update() Method
my_dict = {"name": "Alice", "age": 25}
# Update using another dictionary
my_dict.update({"age": 26, "city": "New York"})
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Example 3: Using Dictionary Comprehension
my_dict = {"a": 1, "b": 2, "c": 3}
# Increase each value by 1
my_dict = {key: value + 1 for key, value in my_dict.items()}
print(my_dict) # Output: {'a': 2, 'b': 3, 'c': 4}
Example 4: Updating a Nested Dictionary
my_dict = {
"name": "Alice",
"contact": {"email": "alice@[Link]", "phone": "123-456-7890"} }
# Update email in the nested dictionary
my_dict["contact"]["email"] = "alice@[Link]"
# Add address to the nested dictionary
my_dict["contact"]["address"] = "123 Main St"
print(my_dict)
# Output: {'name': 'Alice', 'contact': {'email': 'alice@[Link]', 'phone':
'123-456-7890', 'address': '123 Main St'}}
3.7 DICTIONARY METHODS IN PYTHON
Dictionaries in Python come with several built-in methods that help in performing common operations like
adding, accessing, modifying, or deleting key-value pairs. These methods provide a simple interface for
managing and manipulating dictionary data. Below is a description of the common dictionary methods and
example:
1. clear()
Description: Removes all key-value pairs from the dictionary.
Example:
my_dict = {"a": 1, "b": 2}
GE3151 Problem Solving and Python Programming 32
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
my_dict.clear()
print(my_dict) # Output: {}
2. copy()
Description: Returns a shallow copy of the dictionary. Changes to the copy do not affect the original.
Example:
my_dict = {"a": 1, "b": 2}
copy_dict = my_dict.copy()
print(copy_dict) # Output: {'a': 1, 'b': 2}
3. fromkeys()
Description: Creates a new dictionary with keys from the specified iterable and values set to a default
value.
Example:
my_dict = [Link](["a", "b"], 0)
print(my_dict) # Output: {'a': 0, 'b': 0}
4. get()
Description: Returns the value of a specified key, or a default value if the key is not found.
Example:
my_dict = {"a": 1, "b": 2}
value = my_dict.get("a", "Not Found")
print(value) # Output: 1
5. items()
Description: Returns a view object that contains the key-value pairs as tuples.
Example:
my_dict = {"a": 1, "b": 2}
items = my_dict.items()
print(items) # Output: dict_items([('a', 1), ('b', 2)])
6. keys()
Description: Returns a view object containing all the keys of the dictionary.
Example:
my_dict = {"a": 1, "b": 2}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b'])
7. pop()
Description: Removes and returns the value associated with the specified key.
Example:
my_dict = {"a": 1, "b": 2}
value = my_dict.pop("a")
print(value) # Output: 1
8. popitem()
Description: Removes and returns a random key-value pair (last pair in Python 3.7+).
Example:
my_dict = {"a": 1, "b": 2}
key, value = my_dict.popitem()
print(key, value) # Output: b 2 (or a 1 depending on the version)
9. setdefault()
Description: Returns the value for the specified key if it exists. If the key doesn't exist, it inserts the key
with a default value and returns that.
GE3151 Problem Solving and Python Programming 33
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Example:
my_dict = {"a": 1}
value = my_dict.setdefault("b", 2)
print(value) # Output: 2
print(my_dict) # Output: {'a': 1, 'b': 2}
10. update()
Description: Updates the dictionary with key-value pairs from another dictionary or iterable.
Example:
my_dict = {"a": 1, "b": 2}
my_dict.update({"a": 10, "d": 4})
print(my_dict) # Output: {'a': 10, 'b': 2, 'd': 4}
11. values()
Description: Returns a view object containing all the values of the dictionary.
Example:
my_dict = {"a": 1, "b": 2}
values = my_dict.values()
print(values) # Output: dict_values([1, 2])
3.8 DICTIONARY FUNCTIONS IN PYTHON
Python provides several built-in functions that can be used with dictionaries. These functions allow you to
perform various operations such as checking the type, length, and existence of keys or values in a dictionary.
Below is a list of commonly used dictionary functions, along with descriptions and examples.
Function Description Syntax Example
Returns the number of key-value pairs len(my_dict)
len() len(dictionary)
in a dictionary. Output: 3
sorted(my_dict)
sorted()
Returns a sorted list of the keys in the sorted(dictionary) Output: ['a', 'b',
dictionary. 'c']
Checks if a specified key exists in the 'a' in my_dict
in key in dictionary
dictionary. Output: True
Checks if a specified key does not exist key not in 'd' not in my_dict
not in
in the dictionary. dictionary Output: True
dict([('a', 1),
Creates a new dictionary from a ('b', 2)])
dict() sequence of key-value pairs (tuples or dict(iterable)
Output: {'a': 1, 'b':
lists). 2}
dict(zip(['a',
Combines two iterables into a 'b'], [1, 2]))
dict(zip(keys,
zip() dictionary, using the first iterable as values)) Output: {'a': 1, 'b':
keys and the second as values. 2}
set(my_dict)
set()
Returns a set containing the keys of a set(dictionary) Output: {'a', 'b',
dictionary. 'c'}
all(my_dict)
all()
Returns True if all the keys in the all(dictionary) Output: True (if all keys
dictionary evaluate to True (non-zero). are truthy)
any(my_dict)
any()
Returns True if any key in the any(dictionary) Output: True (if any
dictionary evaluates to True (non-zero). key is truthy)
GE3151 Problem Solving and Python Programming 34
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
3.9 ILLUSTRATIVE PROBLEMS
1. Write a program to calculate the square root of a given number using a function.
# Function to calculate square root
def sqrt(num):
if num < 0:
return "Cannot calculate square root of a negative number"
return [Link](num)
# Input from the user
num = float(input("Enter a number to find its square root: "))
# Calling the function and displaying the result
result = sqrt(num)
print(f"The square root of {num} is: {result}")
2. Create a program to find the GCD of two numbers using a function.
# Function to calculate GCD
def find_gcd(a, b):
while b:
a, b = b, a % b
return a
# Input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calling the function and displaying the result
gcd = find_gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is: {gcd}")
3. Develop a program to compute the LCM of two numbers using a function.
The function calculates the LCM using the formula:
∣𝑎×𝑏 ∣
𝐿𝐶𝑀(𝑎, 𝑏) =
𝐺𝐶𝐷(𝑎, 𝑏)
# Function to find the GCD of two numbers
def find_gcd(x, y):
while y:
x, y = y, x % y
return x
# Function to find the LCM of two numbers
def find_lcm(a, b):
# Calculate LCM using the formula LCM(a, b) = abs(a * b) // GCD(a, b)
gcd = find_gcd(a, b)
lcm = abs(a * b) // gcd
return lcm
# Input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calling the function to find the LCM
lcm = find_lcm(num1, num2)
# Displaying the result
print(f"The LCM of {num1} and {num2} is: {lcm}")
4. Write a program to perform exponentiation on a given number using a function.
# Function to perform exponentiation
def power(base, exponent):
return base ** exponent
# Input from the user
base = float(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
GE3151 Problem Solving and Python Programming 35
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Calling the function to calculate exponentiation
result = power(base, exponent)
# Displaying the result
print(f"{base} raised to the power of {exponent} is: {result}")
5. Implement a program to demonstrate the use of an enumerated function.
# List of days and corresponding tasks
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"]
tasks = [
"Go for a run",
"Attend meetings",
"Work on a project",
"Grocery shopping",
"Finish up reports",
"Relax and enjoy",
"Rest and prepare for the week"]
# Using enumerate() to loop through days and tasks
for index, (day, task) in enumerate(zip(days, tasks), start=1):
print(f"Day {index} ({day}): {task}")
6. Create a program to calculate the sum of elements in a list.
# Define a list of numbers
numbers = [10, 20, 30, 40, 50]
# Calculate the sum of the list
total_sum = sum(numbers)
# Display the result
print(f"The sum of the elements in the list is: {total_sum}")
7. Design a Python program that acts as a calculator to add, subtract, multiply, and divide two
numbers using functions.
# Function to add two numbers
def add(a, b):
return a + b
# Function to subtract two numbers
def subtract(a, b):
return a - b
# Function to multiply two numbers
def multiply(a, b):
return a * b
# Function to divide two numbers
def divide(a, b):
if b == 0:
return "Error! Division by zero."
return a / b
# Main program
print("Simple Calculator")
print("Choose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Get user choice
choice = input("Enter choice (1/2/3/4): ")
# Get input numbers
try:
num1 = float(input("Enter first number: "))
GE3151 Problem Solving and Python Programming 36
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numeric values.")
exit()
# Perform the chosen operation
if choice == '1':
print(f"The result is: {add(num1, num2)}")
elif choice == '2':
print(f"The result is: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid choice! Please select a valid operation.")
8. Write a Python program to perform linear search and find an item in an unordered list.
# Linear search function
def linear_search(lst, target):
for index, element in enumerate(lst):
if element == target:
return index # Return the index if the item is found
return -1 # Return -1 if the item is not found
# Main program
numbers = [4, 7, 1, 9, 12, 5, 3] # Example unordered list
print("List:", numbers)
# Input the target to search for
target = int(input("Enter the number to search for: "))
# Perform the search
result = linear_search(numbers, target)
# Display the result
if result != -1:
print(f"Number {target} found at index {result}.")
else:
print(f"Number {target} not found in the list.")
9. Develop a Python program to implement binary search using a list.
# Binary search function
def binary_search(lst, target):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2 # Calculate the middle index
if lst[mid] == target:
return mid # Target found, return its index
elif lst[mid] < target:
low = mid + 1 # Search in the right half
else:
high = mid - 1 # Search in the left half
return -1 # Target not found
# Main program
numbers = [1, 3, 5, 7, 9, 11, 13, 15] # Example sorted list
print("Sorted List:", numbers)
# Input the target to search for
GE3151 Problem Solving and Python Programming 37
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
target = int(input("Enter the number to search for: "))
# Perform the search
result = binary_search(numbers, target)
# Display the result
if result != -1:
print(f"Number {target} found at index {result}.")
else:
print(f"Number {target} not found in the list.")
10. Bubble Sort (List)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break
return arr
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
print("Bubble Sort Result:", bubble_sort(arr))
11. Selection Sort (Tuple)
Selection Sort works by repeatedly finding the minimum element from the unsorted part and swapping it
with the first unsorted element.
def selection_sort(arr):
arr = list(arr) # Convert tuple to list because tuples are immutable
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return tuple(arr) # Convert list back to tuple
# Example usage:
arr = (64, 34, 25, 12, 22, 11, 90)
print("Selection Sort Result:", selection_sort(arr))
12. Insertion Sort (List)
Insertion Sort builds the final sorted array one item at a time by repeatedly taking one element from the
unsorted part and inserting it into the correct position.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
GE3151 Problem Solving and Python Programming 38
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
print("Insertion Sort Result:", insertion_sort(arr))
13. Merge Sort (Tuple)
Merge Sort is a divide-and-conquer algorithm that divides the list into two halves, recursively sorts each
half, and then merges them.
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
sorted_list = []
while left and right:
if left[0] < right[0]:
sorted_list.append([Link](0))
else:
sorted_list.append([Link](0))
sorted_list.extend(left)
sorted_list.extend(right)
return sorted_list
# Example usage:
arr = (64, 34, 25, 12, 22, 11, 90)
print("Merge Sort Result:", merge_sort(arr))
14. Quick Sort (List)
Quick Sort is another divide-and-conquer algorithm. It picks a pivot element, partitions the list into two
sublists (elements less than the pivot and elements greater than the pivot), and recursively sorts the sublists.
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2] # Choose the middle element as pivot
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
print("Quick Sort Result:", quick_sort(arr))
15. Problem Statement: Student Marks Statement using Dictionary
a. Input: A dictionary with student names as keys and their respective marks as values.
b. Processing: For each student, calculate their grade based on the marks.
▪ A+ for marks ≥ 90
▪ A for marks between 80 and 89
▪ B+ for marks between 70 and 79
GE3151 Problem Solving and Python Programming 39
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
▪ B for marks between 60 and 69
▪ C+ for marks between 50 and 59
▪ C for marks between 40 and 49
▪ F for marks < 40
c. Calculate the total marks of all students.
d. Calculate the average marks of all students.
Python Program
def calculate_grade(marks):
if marks >= 90:
return 'A+'
elif marks >= 80:
return 'A'
elif marks >= 70:
return 'B+'
elif marks >= 60:
return 'B'
elif marks >= 50:
return 'C+'
elif marks >= 40:
return 'C'
else:
return 'F'
def generate_marks_report(students):
total_marks = 0
total_students = len(students)
print("Student Marks Report")
print("-" * 40)
print(f"{'Student Name':<20} {'Marks':<10} {'Grade':<5}")
print("-" * 40)
# Iterate through each student in the dictionary
for name, marks in [Link]():
grade = calculate_grade(marks)
total_marks += marks
print(f"{name:<20} {marks:<10} {grade:<5}")
# Calculate average marks
average_marks = total_marks / total_students if total_students > 0 else 0
print("-" * 40)
print(f"Total Marks: {total_marks}")
print(f"Average Marks: {average_marks:.2f}")
# Example usage:
students = {
'Alice': 85,
'Bob': 92,
'Charlie': 78,
'David': 88,
'Eve': 66
}
generate_marks_report(students)
16. Retail Bill Preparation
GE3151 Problem Solving and Python Programming 40
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
def generate_bill(items, quantities):
total_cost = 0
print("Retail Bill")
print("-" * 40)
print(f"{'Item':<20} {'Quantity':<10} {'Price per unit':<15} {'Total
cost':<10}")
print("-" * 40)
# Iterate through each item and calculate the cost
for item, price in [Link]():
if item in quantities: # Check if the item has been purchased
quantity = quantities[item]
total_item_cost = price * quantity
total_cost += total_item_cost
print(f"{item:<20} {quantity:<10} {price:<15} {total_item_cost:<10}")
print("-" * 40)
print(f"{'Total Cost':<35} {total_cost:<10}")
print("-" * 40)
# Example usage:
items = {
'Apple': 2.5,
'Banana': 1.2,
'Orange': 3.0,
'Milk': 1.5,
'Eggs': 2.0
}
# Quantities purchased by the customer
quantities = {
'Apple': 4,
'Banana': 6,
'Orange': 3,
'Milk': 2,
'Eggs': 1
}
generate_bill(items, quantities)
NOTES
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
GE3151 Problem Solving and Python Programming 41
PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
GE3151 Problem Solving and Python Programming 42