0% found this document useful (0 votes)
32 views

Module 3.2.1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Module 3.2.1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ALGORITHMIC THINKING WITH PYTHON

Prof. Sarju S
24 October 2024
Module 3

Page 2
Module 3

► SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop.

► SEQUENCE DATA TYPES IN PYTHON - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).

► DECOMPOSITION AND MODULARIZATION* :- Problem decomposition as a strategy for


solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values

Page 3 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Python Lists

Page 4
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 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 8 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
We Already Use Lists!

for i in [5, 4, 3, 2, 1] : 5
print(i) 4
print('Blastoff!') 3
2
1
Blastoff!

Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
List operations

Page 12
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 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 17 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 18 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Lists Can Be Sliced Using :

names = ["Alice", "Bob",


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

last_three = names[-3:]

print(last_three)

Page 19 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 20 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 21 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 22 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 23 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 24 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 25 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
List methods

Page 26
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 27 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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
► Inserts an element at a specified position. numbers.insert(2, 25)
insert() print(numbers)
► Syntax: list.insert(index, value) # Output: [10, 20, 25, 30, 40,
50]

Page 28 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 29 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 30 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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
pop() # Output: [10, 30, 40, 50]
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 31 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 32 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
List Methods
Method Description Example
numbers = [10, 20, 30, 40, 50]
► Reverses the elements of the list in place. # Reverses the list
reverse() numbers.reverse()
► Syntax: list.reverse() print(numbers)
# Output: [50, 40, 30, 20, 10]

Page 33 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Best Friends: Strings and Lists

s = "hello"
lst = list(s)
print(lst) # 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 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 36 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 37 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 38 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 39 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 40 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 41 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 42 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 43 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

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

Page 44 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Thank You

Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai (Autonomous)
[email protected]

Page 45 Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective content creators.
Document is compiled exclusively for study purpose and shall not be used for commercial purpose.

You might also like