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

Module 3.2.1 Lists PDF

Uploaded by

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

Module 3.2.1 Lists PDF

Uploaded by

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

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
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 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
3
2
1

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))
4
as a string...) >>>

Page 9
Lists and Definite Loops

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
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 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'
Traceback
must make a new string to make any TypeError: 'str' object does not support item
change assignment
>>> x = fruit.lower()
>>> print(x)
Banana

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


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

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 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. print(numbers)
insert()
► 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() numbers.append(40)
► Syntax: list.append(value)
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]

Page 32
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 33
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 34
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.

Page 35
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 36
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 37
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.

Page 38
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.

Page 39
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.

Page 40
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.

Page 41
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 42

You might also like