0% found this document useful (0 votes)
17 views92 pages

7877 50 354 Module 3

The document provides an overview of Python lists, explaining their characteristics, such as being ordered collections of items that can hold various data types. It covers list operations, including indexing, slicing, concatenation, and methods for modifying lists like append, insert, and remove. Additionally, it discusses the mutability of lists and demonstrates how to manipulate list elements using various techniques.

Uploaded by

Aann Mariya Sabu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views92 pages

7877 50 354 Module 3

The document provides an overview of Python lists, explaining their characteristics, such as being ordered collections of items that can hold various data types. It covers list operations, including indexing, slicing, concatenation, and methods for modifying lists like append, insert, and remove. Additionally, it discusses the mutability of lists and demonstrates how to manipulate list elements using various techniques.

Uploaded by

Aann Mariya Sabu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

DEPARTMENT OF ELECTRONICS & COMPUTER ENGINEERING

Python Basics for Machine Learning

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 collection allows us to put many values in a single “variable”


► A collection is nice because we can carry all many values around in one
convenient package.

friends = [ 'Joseph', 'Glenn', 'Sally' ]

carryon = [ 'socks', 'shirt', 'perfume' ]

► 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

► List constants are surrounded by [ ]


and the elements in the list are
>>> print([1, 24, 76])
separated by commas [1, 24, 76]

>>> print(['red', 'yellow', 'blue'])


['red', 'yellow', 'blue’]

>>> print(['red', 24, 98.6])


['red', 24, 98.6]

► 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]

► Lists of integers can also be built using >>> naturals=list(range(1,11))


the range() and list() functions >>> print(naturals)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> mul5=list(range(10,50,5))
>>> print(mul5)
[10, 15, 20, 25, 30, 35, 40, 45]

Page 6
Looking Inside Lists

► Just like strings, we can get at any single


element in a list using an index
specified in square brackets

Joseph Glenn Sally

0 1 2

>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]


>>> print(friends[1])
Glenn

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?

► The len() function takes a list as a >>> greet = 'Hello Bob'


parameter and returns the number of >>> print(len(greet))
elements in the list 9

► Actually len() tells us the number of >>> x = [ 1, 2, 'joe', 99]


elements of any set or sequence (such >>> print(len(x))
as a string...) 4
>>>

Page 9
Lists and Definite Loops - Best Pals

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends :
print('Happy New Year:', friend)
Happy New Year: Joseph
print('Done!')
Happy New Year: Glenn
Happy New Year: Sally
Done!
z = ['Joseph', 'Glenn', 'Sally']
for x in z :
print('Happy New Year:’, x)
print('Done!')

Page 10
Concatenating Lists Using +

► We can create a new list by adding two >>> a = [1, 2, 3]


existing lists together >>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]

Page 12
Repeats a List Using *

► The * operator repeats a list a given >>> binary=[0,1]


number of times: >>> bytesequence=binary*4
>>> print(bytesequence)
[0, 1, 0, 1, 0, 1, 0, 1]

Page 13
Equality operator works well on lists

► It checks if two lists have the same >>> even=[2,4,6,8]


elements. >>> mul2=[2,4,6,8]
>>> print(even==mul2)
True

>>> 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 = [9, 41, 12, 3, 74, 15]


>>> t[1:3]
[41,12]

>>> 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 :

names = ["Alice", "Bob",


"Charlie", "David", "Emmanuel",
"Fiona"]

last_three = names[-3:]

print(last_three)

Page 18
Lists are Mutable

► Strings are “immutable” - we cannot >>> fruit = 'Banana'


change the contents of a string - we >>> fruit[0] = 'b'
must make a new string to make any Traceback
change TypeError: 'str' object does not
support item assignment
>>> x = fruit.lower()
>>> print(x)
Banana

>>> lotto = [2, 14, 26, 41, 63]


>>> print(lotto)
► Lists are “mutable” - we can change an [2, 14, 26, 41, 63]
element of a list using the index >>> lotto[2] = 28
operator >>> print(lotto)
[2, 14, 28, 41, 63]

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.

► By leveraging slicing, you can replace, insert, or remove elements in a list.

Page 20
Replacing Elements Using the Slice Operator

► # Replacing a single element


► numbers = [1, 2, 3, 4, 5]
► numbers[2:3] = [10] # Replace element at index 2 (value 3) with 10
► print(numbers) # Output: [1, 2, 10, 4, 5]

► # Replacing multiple elements


► numbers[1:3] = [20, 30] # Replace elements at index 1 and 2 with 20, 30
► print(numbers) # Output: [1, 20, 30, 4, 5]

Page 21
Replacing Elements Using the Slice Operator

► # Replacing 2 elements with 3 elements (expanding the list)


► numbers = [1, 2, 3, 4, 5]
► numbers[1:3] = [20, 30, 40]
► print(numbers) # Output: [1, 20, 30, 40, 4, 5]

► # Replacing 3 elements with 1 element (shrinking the list)


► numbers[1:4] = [50]
► print(numbers) # Output: [1, 50, 4, 5]

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]

► # Inserting in the middle


► numbers[3:3] = [20, 30]
► print(numbers) # Output: [10, 1, 2, 20, 30, 3, 4, 5]

► # Inserting at the end


► numbers[len(numbers):] = [40]
► print(numbers) # Output: [10, 1, 2, 20, 30, 3, 4, 5, 40]
Page 23
Removing Elements Using the Slice Operator
► You can remove elements from a list by assigning an empty list ([]) to a slice.
► numbers = [1, 2, 3, 4, 5]

► # Removing a single element


► numbers[1:2] = [] # Remove element at index 1 (value 2)
► print(numbers) # Output: [1, 3, 4, 5]

► # Removing multiple elements


► numbers[1:3] = [] # Remove elements at index 1 and 2 (values 3 and 4)
► print(numbers) # Output: [1, 5]

► # Removing all elements


► numbers[:] = [] # Remove all elements (empty the list)
► print(numbers) # Output: []
Page 24
List Methods
Method Description
index() Returns the index of the first occurrence of the specified value.

insert() Inserts a specified value at a specified position (index) in the list.


append() Adds a value to the end of the list.
Extends the list by appending elements from another iterable
extend()
(list, tuple, etc.).
remove() Removes the first occurrence of the specified value from the list.
Removes and returns the element at a specified index (default is
pop()
the last element).
Returns the number of times a specified value appears in the
count()
list.
Sorts the list in ascending order (can be customized to sort in
sort()
descending order).
reverse() Reverses the elements of the list in place.

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]

# Remove and return the element at index 1


► Removes and returns the element at removed_element = numbers.pop(1)
a specified position. print(removed_element) # Output: 20
print(numbers)
► If no index is provided, removes and # Output: [10, 30, 40, 50]
pop()
returns the last element.
► Syntax: list.pop(index) (index # Remove and return the last element
is optional) removed_element = numbers.pop()
print(removed_element) # Output: 50
print(numbers) # Output: [10, 30, 40]

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]

# Using max() to find the largest


number in the list
► This function returns the highest value in largest_number = max(numbers)
max()
the list.
# Printing the result
print("The largest number is:",
largest_number)
#Output: The largest number is: 10

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

s = "apple banana cherry“ s2 = "apple,banana,cherry"


# Default delimiter is space # Splitting by comma
fruits = s.split() fruits2 = s2.split(",")
print(fruits) print(fruits2)
# Output: ['apple', 'banana', 'cherry'] # Output: ['apple', 'banana', 'cherry']

► The split() method is used to split a string into a list, based on a


specified delimiter.
► By default, split() breaks the string at spaces, but you can specify any
character as the delimiter.
► Syntax: string.split(delimiter)

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 = ["apple", "banana", "cherry", "date"]


print(fruits[1]) # Output: banana

fruits[3] = "dragonfruit"
print(fruits) # Output: ["apple", "banana", "cherry",
"dragonfruit"]

Page 36
Exercises - List Slicing

► Objective: How to use slicing to access parts of a list.


► Instructions:
► Create a list of numbers from 1 to 10.

► Print the first 5 elements of the list using slicing.

► Print the last 3 elements using slicing.

# Step 1: Creating the list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Step 2: Printing the first 5 elements


print(numbers[:5]) # Output: [1, 2, 3, 4, 5]

# Step 3: Printing the last 3 elements


print(numbers[-3:]) # Output: [8, 9, 10]

Page 37
Exercises - List Methods (Append, Insert, Remove)

► Objective: Practice the append(), insert(), and remove() methods.


► Instructions:
► Start with an empty list called colors.

► Use append() to add "red", "green", and "blue" to the list.

► Use insert() to add "yellow" at the second position.

► Use remove() to remove "green" from the list.

► Print the final list.

Page 38
# Step 1: Creating an empty list
colors = []

# Step 2: Using append() to add elements


colors.append("red")
colors.append("green")
colors.append("blue")

# Step 3: Using insert() to add "yellow" at the second


position
colors.insert(1, "yellow")

# Step 4: Using remove() to remove "green"


colors.remove("green")

# Step 5: Printing the final list


print(colors) # Output: ['red', 'yellow', 'blue']

Page 39
Exercises - List Methods (Append, Insert, Remove)

► Objective: Practice the append(), insert(), and remove() methods.


► Instructions:
► Start with an empty list called colors.

► Use append() to add "red", "green", and "blue" to the list.

► Use insert() to add "yellow" at the second position.

► Use remove() to remove "green" from the list.

► Print the final list.

Page 40
# Step 1: Creating an empty list
colors = []

# Step 2: Using append() to add elements


colors.append("red")
colors.append("green")
colors.append("blue")

# Step 3: Using insert() to add "yellow" at the second


position
colors.insert(1, "yellow")

# Step 4: Using remove() to remove "green"


colors.remove("green")

# Step 5: Printing the final list


print(colors) # Output: ['red', 'yellow', 'blue']

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].

► Write a loop to find the largest number in the list.

► Print the largest number.


# Step 1: Creating the list of numbers
numbers = [12, 75, 34, 99, 45, 67]

# Step 2: Finding the largest number


largest = numbers[0]
for num in numbers:
if num > largest:
largest = num

# Step 3: Printing the largest number


print("The largest number is:", largest) # Output: 99
Page 42
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].

► Write a loop to find the largest number in the list.

► Print the largest number.


# Step 1: Creating the list of numbers
numbers = [12, 75, 34, 99, 45, 67]

# Step 2: Finding the largest number


largest = numbers[0]
for num in numbers:
if num > largest:
largest = num

# Step 3: Printing the largest number


print("The largest number is:", largest) # Output: 99
Page 43
Exercises - Counting Occurrences in a List

► Objective: Use the count() method to count occurrences of a value in a list.


► Instructions
► Create a list: ["apple", "banana", "cherry", "apple", "apple", "banana"].
► Count how many times "apple" appears in the list.
► Count how many times "banana" appears in the list.

fruits = ["apple", "banana", "cherry", "apple", "apple", "banana"]

apple_count = fruits.count("apple")

banana_count = fruits.count("banana")

print("Apple appears", apple_count, "times.") # Output: 3


print("Banana appears", banana_count, "times.") # Output: 2

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].

► Reverse the order of the list.

► Print the reversed list.

# Step 1: Creating the list of numbers


numbers = [10, 20, 30, 40, 50]

# Step 2: Reversing the list


numbers.reverse()

# Step 3: Printing the reversed list


print(numbers) # Output: [50, 40, 30, 20, 10]

Page 45
Exercises - Remove Duplicates from a List

► Objective: Remove duplicate elements from a list using a loop or set.


► Approach:
► Create an empty list to store unique elements.

► 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]

# List to store unique elements


unique_list = []

# Iterate over the original list


for element in original_list:
# If the element is not already in unique_list, append it
if element not in unique_list:
unique_list.append(element)

# Print the unique list


print("Original list:", original_list)
print("List without duplicates:", unique_list)

Page 47
Python Tuple

Page 4
Introduction to Python Tuples

► Definition: A tuple is an ordered collection in Python used to store multiple


items in a single variable. It’s similar to a list but with one key difference:
tuples are immutable.

► Syntax: Defined using parentheses ( ). Items are separated by commas.

► Example: my_tuple = (1, 2, 3, "apple", "banana")


Characteristics of Tuples

► Ordered: Tuples maintain the order of elements, so each item has a specific
index.

► Immutable: Once a tuple is created, its elements cannot be altered, making


them unchangeable.

► 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

► Empty Tuple: empty_tuple = ()


► Useful when you want a variable to hold an immutable empty collection.

► Single Element Tuple: single_element = (42,)


► Must include a comma after the element to differentiate from just using
parentheses.

► Multiple Elements: my_tuple = (10, 20, 30, "hello", "world")


► Any data types can be mixed within a tuple.
Accessing Tuple Elements

► Indexing: Use the index number to access elements.


► Example: fruits = ("apple", "banana", "cherry"), fruits[1] returns "banana".

► Negative Indexing: Access elements from the end by using negative indices.
► Example: fruits[-1] returns "cherry".

► Slicing: Extract a subset of the tuple using : notation.


► Example: fruits[0:2] returns ("apple", "banana").
Operations on Tuples

► Concatenation: Join two tuples using +.


► Example: tuple1 = (1, 2), tuple2 = (3, 4), result = tuple1 + tuple2 yields (1,
2, 3, 4).

► Repetition: Repeat elements in a tuple using *.


► Example: repeat_tuple = ("hello",) * 3 results in ("hello", "hello", "hello").

► Membership Test: Check if an item exists within a tuple using in.


► Example: "apple" in fruits returns True if "apple" is in fruits.
Tuple Functions and Methods

► len(tuple): Returns the total number of elements.


► Example: len((1, 2, 3)) returns 3.

► max(tuple) and min(tuple): Find the largest or smallest element,


respectively (only for comparable elements).
► Example: max((1, 5, 3)) returns 5.

► tuple(): Converts other data structures (like lists) into tuples.


► Example: tuple([1, 2, 3]) returns (1, 2, 3).
Advantages of Using Tuples

► Performance: Faster to process than lists due to immutability.

► 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

► Create a Tuple: Define a tuple named fruits # Create a Tuple


with the values "apple", "banana", "cherry", fruits = ("apple", "banana", "cherry", "date")
"date".
# Access Elements
► Access Elements:
print(fruits[0]) # Output: apple
► Print the first and last elements of the fruits tuple.
print(fruits[-1]) # Output: date
► Use negative indexing to print "cherry". print(fruits[-2]) # Output: cherry
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

colors = ("red", "green", "blue", "yellow", "orange")


► Define a tuple colors = ("red", "green",
"blue", "yellow", "orange"). # Slicing examples
► Slice the tuple to print the first three colors.
print(colors[0:3])
► Slice the tuple to print the last two colors.
# Output: ("red", "green", "blue")
► Slice the tuple to print colors from the second to
the fourth element.
print(colors[-2:])
# Output: ("yellow", "orange")

print(colors[1:4])
# Output: ("green", "blue", "yellow")
Classroom Exercises

person = ("Alice", 25, "Engineer")


► Create a tuple person = ("Alice", 25,
"Engineer"). # Unpack into variables
name, age, profession = person
► Unpack the tuple into three variables: name, age,
and profession.
► Print each variable to confirm the values. print(name)
# Output: Alice

print(age)
# Output: 25

print(profession)
# Output: Engineer
Problem 1: Inventory Management System for a Store

► A retail store wants to create an inventory system that stores each


item as a tuple containing:
► The item name (string)
► The quantity in stock (integer)
► The unit price (float)
► The store needs to:
► Calculate the total value of the stock for each item.
► Find the item with the highest value in stock.
► Write code to:
► Define a list of tuples to represent the inventory.
► Calculate and display the total stock value for each item.
► Find and print the item with the highest total stock value.
# Inventory data as tuples (item_name, quantity, unit_price)
inventory = [
("Laptop", 5, 1200.00),
("Headphones", 15, 100.00),
("Mouse", 50, 25.00),
("Keyboard", 20, 45.00),
("Monitor", 10, 300.00) Total stock values:
] Laptop: $6000.00
Headphones: $1500.00
Mouse: $1250.00
Keyboard: $900.00
print("Total stock values:") Monitor: $3000.00
highest_value = 0
Item with the highest stock value:
highest_value_item = None Laptop - Total Value: $6000.00

for item in inventory:


name, price, quantity = item

total_value = quantity * price


print(f"{name}: ${total_value:.2f}")

# Track the item with the highest total value


if total_value > highest_value:
highest_value = total_value
highest_value_item = item

print("\nItem with the highest stock value:")


print(f"{highest_value_item[0]} - Total Value: ${highest_value:.2f}")
Problem 2: Employee Management System

► A company wants to manage its employee information and includes


each employee as a tuple containing:
► Employee name (string)
► Department (string)
► Monthly salary (float)
► The company needs to:
► Display all employees who have a monthly salary above a specified threshold.
► Find the total annual payroll expense for all employees in the company.
► Write code to:
► Define a list of tuples with employee information.
► Display employees earning above a salary threshold.
► Calculate and display the total annual payroll expense.
# Employee data as tuples (name, department, monthly_salary)
employees = [
Enter the monthly salary threshold to filter employees: 4000
("Alice", "HR", 3000.00),
Employees earning above $4000.0 per month:
("Bob", "Engineering", 4500.00), Bob (Engineering) - $4500.00
("Charlie", "Sales", 4000.00), Eve (Engineering) - $5000.00

("Diana", "Marketing", 3500.00), Total annual payroll expense: $240000.00


("Eve", "Engineering", 5000.00)
]
# Input the salary threshold from the user
threshold = float(input("Enter the monthly salary threshold to filter employees: "))

# Display employees with monthly salary above a certain threshold


print(f"Employees earning above ${threshold} per month:")
for employee in employees:
name, department, salary = employee
if salary > threshold: It means the total amount of money a company pays all its employees in a year
print(f"{name} ({department}) - ${salary:.2f}")
# Calculate total annual payroll expense
total_annual_expense = 0
for employee in employees:
salary = employee[2] # Access the salary from the tuple
total_annual_expense += salary * 12 # Add the annual salary to the total
print(f"\nTotal annual payroll expense: ${total_annual_expense:.2f}")
Python Set

4
Page 2
What is a Set?

► A set is a collection data type that is unordered, unique, mutable


(changeable), and unindexed.
► Unordered: The items do not have a defined order, so they do not maintain the
sequence in which they were added.
► Unique: A set cannot contain duplicate items. If duplicates are added, they will
automatically be removed.
► Mutable: Sets can be changed after they are created, allowing elements to be added or
removed.
► Unindexed: set do not have a specific position or index number.
► Unlike lists or tuples, where each element has a fixed position that you can access using an
index (like list[0] to get the first item), sets do not support this kind of indexing.

Page 3
Creating a Set

► In Python, sets can be created in two main ways:

► Using curly braces {}


► my_set = {1, 2, 3}

► Using the set() function


► my_set = set([1, 2, 3])

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.

► To create an empty set, you need to use the set() function.


► If you write set() with parentheses, Python understands this as 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

► To iterate through a set in Python, you can use a for loop.


► Since sets are unordered collections, the items do not have a specific order when
you iterate over them.
# Define a set with some values
my_set = {10, 20, 30, 40, 50}
40
10
# Use a for loop to iterate through the set
50
for item in my_set:
20
print(item)
30

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

► Python sets support various operations inspired by mathematical set theory


► Union (| or union())
► Combines all elements from two sets, returning a new set with all unique elements from
both.

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

► Python sets support various operations inspired by mathematical set theory


► Intersection (& or intersection())
► Returns a new set containing only the elements found in both sets.

A = {1, 2, 3}
B = {3, 4, 5}
C = A & B # or A.intersection(B)
print(C) # Output: {3}

Page 11
Common Set Operations

► Python sets support various operations inspired by mathematical set theory


► Difference (- or difference())
► Returns a new set with elements that are in the first set but not in the second.

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

► Python sets support various operations inspired by mathematical set theory


► Symmetric Difference (^ or symmetric_difference())
► Returns a new set containing elements found in either of the sets but not in both.

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?

► Sets are useful in situations where:


► Duplicate items are unnecessary: If you need to ensure only unique items, sets
automatically handle duplicates for you.

► Membership Testing: Checking if an item is in a set is generally faster than in lists or


tuples due to the underlying data structure.

► 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

# Display unique customer IDs


print("Unique customers for the day:", unique_customers)
► Problem: A store wants to track the unique customer IDs of people who visit
each day. Each customer has a unique ID, and some customers visit more
than once a day. Create a program that adds customer IDs to a set, then
displays the unique customers for the day.

► 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

Exercise 2: Updating Inventory with New Items

► Problem: A shop has an initial inventory of items but receives a shipment


with new items. Update the inventory with the new items, ensuring there are
no duplicate entries. # Current inventory
inventory = {"apple", "banana", "orange"}

# New shipment with some new and duplicate items


► Instructions new_shipment = {"banana", "grape", "apple", "kiwi"}

Create a set for the current inventory.


# Update inventory with new items
► inventory.update(new_shipment)

► 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

Exercise 3: Removing Out-of-Stock Items

► 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

Exercise 4: Drawing a Random Winner from Participants

► Problem: A school is organizing a raffle with unique student IDs. Write a


program to randomly select a winner from the list of participants using
pop(). # Set of student IDs participating
participants = {101, 102, 103, 104, 105}

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

Exercise 5: Clearing Expired Discounts

► 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

► Instructions discount_codes = {"SAVE10", "WELCOME", "FREESHIP", "DEAL20"}

# Clear all codes


► Create a set of discount codes. discount_codes.clear()

► Use clear() to remove all codes. #print("Discount


Display the empty set
codes after clearing:", discount_codes)
► Display the set to confirm it’s empty.
Discount codes after clearing: set()

https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-discount-codes.py

Page 20
Class Room Exercises

Exercise 5: Clearing Expired Discounts

► 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

Exercise 6: Removing a Product that Failed Quality Check

► 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

► Use discard() to remove a failed product. # Print updated list


print("Products after quality check:", products)
► Print the set to see the updated list of products.
https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/set-quality-check.py
Products after quality check: {'P101', 'P102', 'P104'}

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

► Unordered: Dictionaries do not maintain the order of elements

► Mutable: You can modify the values of a dictionary after creation.

► 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

► You can access values in a dictionary by using their corresponding keys

student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Science"]
}

print(student["name"]) # Output: Alice


print(student["nam"]) # Output: KeyError: 'nam'

► To avoid errors if a key doesn’t exist, use the .get() method:

print(student.get("age", "Key not found")) # Output: 20


Adding or Updating Elements

► To add a new key-value pair or update an existing key, use the


assignment syntax:

student["age"] = 21 # Updates the age to 21


student["grade"] = "A" # Adds a new key 'grade'
Removing Elements

► You can remove elements from a dictionary in multiple ways


► Using del keyword

del student["age"] # Removes the 'age' key-value pair

► Using .pop() method:

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)

python student = {"name": "Alice", "age": 20}


Returns a view of all keys in the print(student.keys())
.keys() # Output: dict_keys(['name', 'age’])
dictionary.

python student = {"name": "Alice", "age": 20}


Returns a view of all values in the print(student.values())
.values() # Output: dict_values(['Alice', 20])
dictionary.

python student = {"name": "Alice", "age": 20}


Returns a view of all key-value pairs as
.items() print(student.items())
tuples.
# Output: dict_items([('name', 'Alice'), ('age', 20)])
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
new_data = {"grade": "A", "age": 21}
Adds or updates multiple key-value pairs from student.update(new_data)
.update() print(student)
another dictionary.
# Output: {'name': 'Alice', 'age': 21, 'grade': 'A’}

python student = {"name": "Alice", "age": 20}


age = student.pop("age")
.pop() Removes a specified key and returns its value. print(age) # Output: 20
print(student) # Output: {'name': 'Alice’}

python student = {"name": "Alice", "age": 20}


Removes and returns the last inserted key- last_item = student.popitem()
.popitem()
value pair. print(last_item) # Output: ('age', 20)
print(student) # Output: {'name': 'Alice'}
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
Removes all elements from the
.clear() student.clear() print(student) # Output: {}
dictionary.

python student = {"name": "Alice", "age": 20} student_copy =


student.copy() student_copy["age"] = 21
Creates a shallow* copy of the print(student) # Output: {'name': 'Alice', 'age': 20}
.copy()
dictionary. print(student_copy) # Output: {'name': 'Alice', 'age': 21}

python keys = ["name", "age", "grade"]


default_value = "Not specified"
Creates a new dictionary with
new_dict = dict.fromkeys(keys, default_value)
.fromkeys() specified keys, each assigned to a
print(new_dict)
given value (or None).
# Output: {'name': 'Not specified', 'age': 'Not specified',
'grade': 'Not specified'}

*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)

► Iterating over values


for value in student.values():
print(value)

► Iterating over key-value pairs

for key, value in student.items():


print(f"{key}: {value}")
Example Use Case: Counting Word Frequencies

► Dictionaries can contain other dictionaries as values, which is helpful for


representing more complex data.

words = ["apple", "banana", "apple", "orange", "banana", "apple"]


word_count = {}
word is a key (like "apple").
word_count[word] refers to the value associated with that key.
for word in words: If YES: returns its current count.
word_count[word] = word_count.get(word, 0) + 1
If NO: returns 0 as default.

print(word_count) # Output: {'apple': 3, 'banana': 2, 'orange': 1}

word = "apple"

word_count[word] = word_count.get(word, 0) + 1 word_count.get("apple", 0) -- not found---returns 0


• This updates the count for the current word in the word_count dictionary: word_count["apple"] = 0 + ---1
• If the word exists in the dictionary, its count is incremented by 1.
• If the word does not exist, it is added to the dictionary with a count of 1.
# Initialize telephone directory
telephone_directory = {}
Nested Dictionaries
# Define all the functions (like cases)
def add_contact(): # Initialize telephone directory
name = input("Enter name: ") telephone_directory = {}
if name in telephone_directory:
► Dictionaries can contain other dictionaries as values,
print("Contact already exists!") which is helpful for
# Define all the functions (like cases)
def add_contact():
else: name = input("Enter name: ")
representing more complex data.
number = input("Enter phone number: ") if name in telephone_directory:
telephone_directory[name] = number print("Contact already exists!")
print("Contact added successfully!") else:
number = input("Enter phone number: ")
def update_contact(): telephone_directory[name] = number
print("Contact added successfully!")
name = input("Enter name to update: ")
if name in telephone_directory:students = { def update_contact():
number = input("Enter new phone number: ")
"student1": {"name": "Alice", "age": name
20},= input("Enter name to update: ")
telephone_directory[name] = number if name in telephone_directory:
"student2":
print("Contact updated successfully!") {"name": "Bob", "age": 22} number = input("Enter new phone number: ")
else: } telephone_directory[name] = number
print("Contact not found!") print("Contact updated successfully!")
else:
def delete_contact(): print("Contact not found!")
name = input("Enter name to delete: ") def delete_contact():
if name in telephone_directory: name = input("Enter name to delete: ")
del telephone_directory[name] if name in telephone_directory:
print("Contact deleted successfully!") del telephone_directory[name]
else: print("Contact deleted successfully!")
print("Contact not found!") else:
print("Contact not found!")
def search_contact():
def search_contact():
name = input("Enter name to search: ") name = input("Enter name to search: ")
if name in telephone_directory: if name in telephone_directory:
print(f"{name}'s phone number is: {telephone_directory[name]}") print(f"{name}'s phone number is:
else: {telephone_directory[name]}")
Exercise

► Create a telephone directory using a dictionary. The name of the individual


and the telephone number will be key and value, respectively. Write a
Python program that allows the user to perform the following operations:
► Add a Contact: Add a new contact with a name and phone number to the directory.
► Update a Contact: Update the phone number of an existing contact.
► Delete a Contact: Remove a contact from the directory.
► Search for a Contact: Look up the phone number of a contact by their name.
► Display All Contacts: Print all contacts in the directory.
► Exit the program.
► Use a menu-driven approach.

You might also like