7877 50 354 Module 3
7877 50 354 Module 3
Page 1
3
Page 2 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Python Lists
4
Page 3
A List is a Kind of Collection
► A list is an ordered set of data values. The values that make up a list are
called its elements or items.
Page 4
List Constants
► A list element can be any Python object >>> print([ 1, [5, 6], 7])
- even another list [1, [5, 6], 7]
>>> print([])
► A list can be empty []
Page 5
List Constants
>>> digits=list(range(10))
>>> print(digits)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mul5=list(range(10,50,5))
>>> print(mul5)
[10, 15, 20, 25, 30, 35, 40, 45]
Page 6
Looking Inside Lists
0 1 2
Page 7
We Already Use Lists!
for i in [5, 4, 3, 2, 1] : 5
print(i) 4
print('Blastoff!') 3
2
1
Blastoff!
Page 8
How Long is a List?
Page 9
Lists and Definite Loops - Best Pals
Page 10
Concatenating Lists Using +
Page 12
Repeats a List Using *
Page 13
Equality operator works well on lists
>>> composite=[4,6,8]
>>> print(even==composite)
False
Page 14
Relational operators also work with lists
>>> prime=[2,3,5] ► Python starts by comparing the first element from each
>>> even=[2,4,6] list.
>>> print(prime>even)
► If they are equal, it goes on to the next element, and so
False
on, until it finds the first pair of elements that are
different and determines the relation between them.
► In this example, prime[0] == even[0].
► Next, prime[1] and even[1] are compared.
► Thus, the resulting relation is ‘<’ and prime > even is thus
False.
► Once the result is determined, the subsequent elements are
skipped.
Page 15
Membership operators can be applied to a list as well
>>> even=[2,4,6,8]
>>> composite=[4,6,8]
>>> print(2 in even)
True
>>> print(2 in composite)
False
Page 16
Lists Can Be Sliced Using :
>>> t[:4]
[9, 41, 12, 3] ► Remember: Just like in strings, the
second number is “up to but not
>>> t[3:] including”
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
Page 17
Lists Can Be Sliced Using :
last_three = names[-3:]
print(last_three)
Page 18
Lists are Mutable
Page 19
Slice operator and mutations
► In Python, the slice operator can be used not only for accessing portions of
sequences but also for modifying mutable sequences like lists.
Page 20
Replacing Elements Using the Slice Operator
Page 21
Replacing Elements Using the Slice Operator
Page 22
Inserting Elements Using the Slice Operator
► You can insert new elements into a list at any position by assigning values to an empty slice
(start:stop with start == stop).
► numbers = [1, 2, 3, 4, 5]
► # Inserting at the beginning
► numbers[0:0] = [10]
► print(numbers) # Output: [10, 1, 2, 3, 4, 5]
Page 26
List Methods
Method Description Example
► Returns the index of the first occurrence of a
specified value. numbers = [10, 20, 30, 40, 50]
index() ► Syntax: list.index(value) print(numbers.index(30))
► Raises: ValueError if the specified value is not # Output: 2
found.
numbers = [10, 20, 30, 40, 50]
# Insert 25 at index 2
numbers.insert(2, 25)
► Inserts an element at a specified position.
insert() print(numbers)
► Syntax: list.insert(index, value) # Output: [10, 20, 25, 30, 40,
50]
Page 27
List Methods
Method Description Example
numbers = [10, 20, 30]
# Adds 40 to the end of the
► Adds an element at the end of the list. list
append()
► Syntax: list.append(value) numbers.append(40)
print(numbers)
# Output: [10, 20, 30, 40]
numbers = [10, 20, 30]
# Adds all elements from the
► Extends the list by appending elements from second list
numbers.extend([40, 50, 60])
extend() another list (or any iterable). print(numbers)
► Syntax: list.extend(iterable) # Output: [10, 20, 30, 40, 50,
60]
Page 28
List Methods
Method Description Example
► Removes the first occurrence of a specified numbers = [10, 20, 30, 40, 30]
value. # Removes the first occurrence of
30
remove() ► Syntax: list.remove(value) numbers.remove(30)
► Raises: ValueError if the specified value is print(numbers)
not found. # Output: [10, 20, 40, 30]
► Returns the number of occurrences of a numbers = [10, 20, 30, 10, 20, 10]
print(numbers.count(10))
count() specified value.
# Output: 3
► Syntax: list.count(value)
Page 29
List Methods
Method Description Example
numbers = [10, 20, 30, 40, 50]
Page 30
List Methods
Method Description Example
numbers = [50, 10, 40, 30, 20]
# Sorts in ascending order
numbers.sort()
► Sorts the list in ascending order by default print(numbers)
(can be customized to sort in descending # Output: [10, 20, 30, 40, 50]
sort()
order).
► Syntax: list.sort(reverse=False) # Sort in descending order
numbers.sort(reverse=True)
print(numbers)
# Output: [50, 40, 30, 20, 10]
Page 31
List Methods
Method Description Example
numbers = [10, 20, 30, 40, 50]
# Reverses the list
► Reverses the elements of the list in place.
reverse() numbers.reverse()
► Syntax: list.reverse() print(numbers)
# Output: [50, 40, 30, 20, 10]
# List of numbers
numbers = [3, 7, 2, 8, 5, 10, 4]
Page 32
List Methods
Method Description Example
# List of numbers
numbers = [3, 7, 2, 8, 5, 10, 4]
# Using min() to find the smallest
number in the list
► This function returns the lowest value in the smallest_number = min(numbers)
min()
list. # Printing the result
print("The smallest number is:",
smallest_number)
#Output: The smallest number is: 2
Page 33
Best Friends: Strings and Lists
str = "hello"
char_list = list(s)
print(char_list ) # Output: ['h', 'e', 'l', 'l', 'o']
► The list() method converts an iterable (like a string) into a list of its
elements
► When used with a string, it breaks the string down into a list of individual
characters
Page 34
Best Friends: Strings and Lists
Page 35
Exercises - Create a List and Access Elements
► Objective: How to create lists, access elements using indexing, and modify list elements.
► Instructions:
► Create a list called fruits with the following elements: "apple", "banana", "cherry",
"date".
► Print the second element in the list.
► Modify the last element of the list to "dragonfruit". Print the modified list.
fruits[3] = "dragonfruit"
print(fruits) # Output: ["apple", "banana", "cherry",
"dragonfruit"]
Page 36
Exercises - List Slicing
Page 37
Exercises - List Methods (Append, Insert, Remove)
Page 38
# Step 1: Creating an empty list
colors = []
Page 39
Exercises - List Methods (Append, Insert, Remove)
Page 40
# Step 1: Creating an empty list
colors = []
Page 41
Exercises - Find the Largest Number in a List
► Objective: How to loop through a list and find the largest element.
► Instructions:
► Create a list of numbers: [12, 75, 34, 99, 45, 67].
► Objective: How to loop through a list and find the largest element.
► Instructions:
► Create a list of numbers: [12, 75, 34, 99, 45, 67].
apple_count = fruits.count("apple")
banana_count = fruits.count("banana")
Page 44
Exercises - Reversing a List
► Objective: Use the reverse() method to reverse the order of elements in a list.
► Instructions:
► Create a list of numbers: [10, 20, 30, 40, 50].
Page 45
Exercises - Remove Duplicates from a List
► Loop through the original list, and for each element, check if it is already in the new
list.
► If the element is not in the new list, add it.
Page 46
# Original list with duplicates
original_list = [1, 3, 2, 4, 3, 2, 5, 1, 6, 5]
Page 47
Python Tuple
Page 4
Introduction to Python Tuples
► Ordered: Tuples maintain the order of elements, so each item has a specific
index.
► Allows Duplicates: Tuples can hold multiple instances of the same value,
e.g., (1, 1, 2, 3).
► Supports Mixed Data Types: Tuples can contain a mix of integers, floats,
strings, or other data types.
Creating Tuples in Python
► Negative Indexing: Access elements from the end by using negative indices.
► Example: fruits[-1] returns "cherry".
► Data Integrity: Useful when data should not be modified after creation,
such as in database records.
► Dictionary Keys: Since tuples are immutable, they can be used as keys in
dictionaries, unlike lists.
► Code Readability: Tuples can signify that data is constant and should not be
changed, making code easier to read and understand.
Classroom Exercises
# Concatenation
even_numbers = (2, 4, 6)
► Concatenation: odd_numbers = (1, 3, 5)
► Create two tuples even_numbers = (2, 4, 6) and numbers = even_numbers + odd_numbers
odd_numbers = (1, 3, 5). print(numbers)
► Concatenate these tuples and store the result in a # Output: (2, 4, 6, 1, 3, 5)
new tuple numbers.
► Repetition: Repeat the tuple ("hello",) three # Repetition
times, and print the result. repeat_tuple = ("hello",) * 3
print(repeat_tuple)
► Membership Test: Check if "banana" is # Output: ("hello", "hello", "hello")
present in the fruits tuple from Exercise 1.
# Membership Test
print("banana" in fruits)
# Output: True
Classroom Exercises
print(colors[1:4])
# Output: ("green", "blue", "yellow")
Classroom Exercises
print(age)
# Output: 25
print(profession)
# Output: Engineer
Problem 1: Inventory Management System for a Store
4
Page 2
What is a Set?
Page 3
Creating a Set
Page 4
Creating an Empty Set
► In Python, curly braces {} are used to create both dictionaries and sets.
► However, when you write {} alone, Python interprets it as an empty dictionary rather
than an empty set.
# Empty set
empty_set = set()
print(type(empty_set)) # Output: <class 'set'>
Page 5
Basic Set Operations
Operation Explanation Example
A = {1, 2, 3}
Add (add()) Adds a single specified element to the set. A.add(4)
Output: {1, 2, 3, 4}
A = {1, 2, 3}
Adds multiple elements from another set or iterable (like a list) to
Update (update()) A.update([4, 5, 6])
the set.
Output: {1, 2, 3, 4, 5, 6}
A = {1, 2, 3}
Removes a specific element from the set; raises an error if the
Remove (remove()) A.remove(2)
element is not found.
Output: {1, 3}
A = {1, 2, 3}
Removes a specific element from the set, but does not raise an
Discard (discard()) A.discard(4)
error if it’s missing.
Output: {1, 2, 3}
A = {1, 2, 3}
A.pop()
Pop (pop()) Removes and returns an arbitrary element from the set.
Output: {2, 3} (removes one item
randomly)
A = {1, 2, 3}
Clear (clear()) Removes all elements from the set, making it empty. A.clear()
Output: set() (an empty set)
Page 7
Iterating through a Set
Note: The order in which items are printed may differ when you run the program because sets do
not maintain a fixed order.
Page 8
Common Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
C = A | B # or A.union(B)
print(C) # Output: {1, 2, 3, 4, 5}
Page 10
Common Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
C = A & B # or A.intersection(B)
print(C) # Output: {3}
Page 11
Common Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
C = A - B # or A.difference(B)
print(C) # Output: {1, 2}
Page 12
Common Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
C = A ^ B # or A.symmetric_difference(B)
print(C) # Output: {1, 2, 4, 5}
Page 13
Why Use Sets?
► Set Operations: If you need to perform union, intersection, or difference, sets make
these tasks straightforward.
Page 14
# Create an empty set to store unique customer IDs
unique_customers = set()
Class Room Exercises # Add customer IDs (some may be duplicates)
unique_customers.add(101)
unique_customers.add(102)
unique_customers.add(103)
unique_customers.add(101) # Duplicate
Exercise 1: Unique Customer Visits unique_customers.add(104)
unique_customers.add(102) # Duplicate
► Instructions
► Use add() to add customer IDs to a set.
► Display the set to see all unique customer IDs.
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-unique-customer.py
Page 16
Class Room Exercises
► Use update() to add new items from a shipment. # Display updated inventory
print("Updated inventory:", inventory)
► Display the updated inventory. Updated inventory: {'banana', 'orange', 'kiwi', 'grape', 'apple'}
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-update-inventory.py
Page 17
Class Room Exercises
► Problem: The store wants to remove specific items from the inventory when
they are out of stock. Use remove() or discard() to handle this.
# Current stock items
inventory = {"apple", "banana", "orange", "kiwi"}
# Remove an out-of-stock item using remove()
Instructions
inventory.remove("banana") # This item exists
► # Try to remove another item using discard() (even if it doesn’t exist)
inventory.discard("mango") # No error even if 'mango' not found
► Create a set with current stock items. # Display updated inventory
print("Updated inventory:", inventory)
► Use remove() to remove an item that’s out of stock.
► Try to use discard() to remove another item (including one that might not exist).
Updated inventory: {'kiwi', 'apple', 'orange'}
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-remove-item.py
Page 18
Class Room Exercises
Instructions
# Randomly select a winner using pop()
► winner = participants.pop()
► Add student IDs to a set. # Show the winner and remaining participants
print("Winner is:", winner)
► Use pop() to randomly remove and display a winner. print("Remaining participants:", participants)
► Ensure the winner is removed from the set. Winner is: 101
Remaining participants: {102, 103, 104, 105}
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-random-winner.py
Page 19
Class Room Exercises
► Problem: A store has a set of discount codes, but all codes have expired, so
they need to be removed. Write a program to clear the discount codes.
# Set of expired discount codes
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-discount-codes.py
Page 20
Class Room Exercises
► Problem: A store has a set of discount codes, but all codes have expired, so
they need to be removed. Write a program to clear the discount codes.
► Instructions
► Create a set of discount codes.
► Use clear() to remove all codes.
► Display the set to confirm it’s empty.
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-discount-codes.py
Page 21
Class Room Exercises
► Problem: A warehouse has a set of products ready for shipment, but one
product fails the quality check and must be removed. Use discard() to
remove it safely without raising an error if it’s missing.
# Set of product IDs ready for shipment
Instructions
products = {"P101", "P102", "P103", "P104"}
►
# One product failed quality check
► Create a set of product IDs. products.discard("P103") # Safe even if product not found
Page 22
Python Dictionary
Page 4
What is a Dictionary?
► A dictionary in Python is a built-in data type that allows you to store and manage data in a
structured way using key-value pairs.
► This means each value is associated with a unique key, making it easy to access, update, or
delete specific elements.
► A dictionary is defined by enclosing key-value pairs within curly braces {}, with each key-
value pair separated by a colon : and pairs separated by commas.
Syntax Example
my_dict = { student = {
"key1": "value1", "name": "Alice",
"key2": "value2", "age": 20,
"key3": "value3" "courses": ["Math", "Science"]
} }
Characteristics of a Dictionary
► Key Uniqueness: Each key in a dictionary must be unique. If a duplicate key is added, the
latest value overwrites the previous one.
► Key Type: Keys must be immutable types (e.g., strings, numbers, tuples), but values can be
of any type.
# Defining a dictionary with keys of immutable types: string, number, and tuple
my_dict = {
"name": "Alice", # String key
42: "Answer to everything", # Integer key
(1, 2): "Point" # Tuple key
}
Accessing Dictionary Elements
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Science"]
}
student.pop("grade", "Key not found") # Removes 'grade' and returns its value
► Using .popitem(): Removes the last inserted key-value pair in Python 3.7+.
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
print(student.get("name")) # Output: Alice
Retrieves value for a specified key; print(student.get("grade", "N/A"))
.get()
returns default if key is not found. # Output: N/A (since "grade" key doesn't exist)
*A shallow copy is a duplicate of an object, but it only copies the references to the elements in the object, not the actual objects themselves. This means
that if the original object contains mutable objects (like lists or dictionaries), both the original and the shallow copy will point to the same objects, so
changes made to mutable elements in one will be reflected in the other.
original = [[1, 2], [3, 4]] # A list of lists Original: [[1, 2], [3, 4]]
shallow = copy.copy(original) # Create a shallow copy Deep: [[99, 2], [3, 4]]
So changing deep[0][0] does not affect the original
shallow[0][0] = 99 # Change an inner element A shallow copy makes a new outer box, but puts the same small boxes inside.
So changing shallow[0][0] also changes original[0][0]. A deep copy makes a new outer box, and new small boxes too..
Iterating Through a Dictionary
► You can use loops to iterate over keys, values, or both in a dictionary
► Iterating over keys
for key in student.keys():
print(key)
word = "apple"