M02-Lecture Notes
M02-Lecture Notes
© Faculty of Management
List
A type of data structure that deals with a list of data
list = ['a','b','c']
• It can also contain both string and integer values within a list
mixed = [4, 5, "seconds"]
Access an Element
To access an element in a list, use the index of the element within a
square bracket [].
• The index is the position of the element.
• Elements can be accessed with either positive indexes or negative indexes.
#Output
Names = ["Jim", "Andrew", "Pam", "Dwight"]
Keep in mind that the index should be within the valid range of the list,
otherwise, it will result in an "IndexError" indicating an index out of range.
List Manipulation
& Operations
© Faculty of Management
List Manipulation & Operations
1. Add an element to a list: append(), insert()
2. Remove an element from a list: pop(), remove()
3. Determine whether specific elements exist in the list:
in/not in operator
4. Combine lists: concatenation(+), multiplication(*) operator
5. Check the length of the list: len()
Add an Element
append()
Add an element to the end of the list.
a= [1, 2, 3] 1 2 3
a.append(4) [0] [1] [2]
print(a)
#output 1 2 3 4
[1, 2, 3, 4] [0] [1] [2] [3]
Add an Element (cont.)
insert(position, value)
Insert an item value at a given position.
a= [1, 2, 3] 1 2 3
a.insert(0, 0) [0] [1] [2]
print(a)
#output 0 1 2 3
[0, 1, 2, 3] [0] [1] [2] [3]
Example: Add an Element
What will be the output of the following code?
a= [1, 2, 3] 1 2 3
a.insert(1, 4) [0] [1] [2]
4
1 4 2 3
[1,4,2,3]
[0] [1] [2] [3]
Delete an Element
pop ()
Remove the item at the given position in the list.
If no index is specified, pop() removes the last item in the list.
#output a b
['a', 'b'] [0] [1]
Delete an Element (cont.)
remove (x)
Remove the first occurrence of a specified element from a list.
#output
a c b
['a', 'c']
[0] [1] [2]
Examples: Delete an Element
pop (index) remove (x)
Remove the item at the given position Remove the first occurrence of a
in the list. specified element from a list.
a c b
a c b
[0] [1] [2]
[0] [1] [2]
list_a.pop(2) list_a.remove('b')
Specific Element Check
in/not in operator
Check if a particular element is inside a list
a= [1, 2, 3]
print(4 in a) 1 2 3
#output : False
[0] [1] [2]
print("3" not in a)
#output : True
Combine Lists
List concatenation (+)
The process of combining or merging multiple lists into a single list
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
# concatenation
list_1_2= list_1 + list_2
print(list_1_2)
[1, 2, 3, 4, 5, 6]
Combine Lists (cont.)
List repetition (*)
The process of creating a new list by repeating the elements of an
existing list a certain number of times.
list_1 = [1, 2, 3]
# repetition
list_1_rep = list_1 *3
print(list_1_rep)
[1, 2, 3, 1, 2, 3, 1, 2, 3 ]
Check the Length
len()
Determine the number of elements in a list.
# length
print(len(list_1_rep))
9
Summary
• A list is an ordered collection of elements, enclosed in square
brackets ([]).
• Lists can store elements of different data types, such as strings,
numbers, or even other lists.
• Elements in a list are indexed, starting from 0 for the first element.
• Lists support various operations like appending, inserting, and
removing elements.
• Lists can be used to implement stacks, queues, and other data
structures.
Data Structure: Dictionary
© Faculty of Management
Dictionary
A dictionary is one of the built-in data structures in Python that
stores and manages collections of data in key-value pairs.
Attendee Sheet
StudentID Name • Key: A unique identifier associated with specific
2001 Ian values (e.g., StudentID, OrderNum, etc).
2002 Elodie • Value: Actual data or information associated
2003 Jake with a specific key
2004 Allegra
Creating a Dictionary
A data structure that stores an unordered collection of items.
• Use curly brackets {} to create a dictionary
• Composed of pairs of key-values
• Items separated by comma The key-value pairs are
separated by colons (:)
dict={key:value,
key:value, Commas separate elements
key:value}
Create a dictionary
webpage_dict={'google': False, #allowed
'youtube': True # blocked}
key:value
Add Key-Value Pairs
Create a dictionary
webpage_dict
value False True
key 'google' 'youtube'
# Create an empty dictionary
webpage_dict = {}
webpage_dict['google'] webpage_dict['youtube']
Modify a Dictionary
Modify existing elements
True → False
webpage_dict
value False True webpage_dict['youtube'] = False
key 'google' 'youtube'
webpage_dict
value False False True webpage_dict['Instagram'] = True # Blocked
key 'google' 'youtube' 'Instagram'
Delete a Key-Value Pair
To delete key-value pairs from a dictionary, you can use the 'del' keyword
followed by the dictionary name and the key you want to remove.
webpage_dict webpage_dict
value False False True value False True
key 'google' 'youtube' 'Instagram' key 'youtube' 'instagram'
Delete!
# Deleting a key-value pair
del webpage_dict['google']
Example: Check Key Exists
Generate a program to check if a specific website is included in the
website blocking status tracker.
webpage_dict.keys()
© Faculty of Management
Loops
Control flow structures that Start
allow a block of code to be
executed repeatedly based limit=input() Loops
on a certain condition.
count=count+1
count<limit True
print(count)
• 'for' statement
• 'while' statement False
print('end')
End
'for' Statement
The for loop traverses the sequence or other iterable objects and
ends the iteration when it reaches the end of the sequence.
• The 'item' variable takes on the value of each item in the sequence, one at a time.
• The code block indented below the 'for' statement is executed for each iteration
of the loop, using the current value of 'item.'
• The loop continues until it reaches the last item in the sequence, which can be a
list, dictionary, string, or any other iterable object.
Example: Print elements from a list
Expected Output
website_list=['google','youtube','instagram'] google
youtube
instagram
website_list=['google','youtube','instagram']
google
for website in website_list: youtube
print(website) instagram
Example: Find all positive numbers
Using the for loop, find all positive numbers from a list.
price_list=[-3, 10, 20, -5, 15, 25]
Example: Find all positive numbers (cont.)
price_list = [-3, 10, 20, -5, 15, 25] -3 10 20 -5 15 25
[0] [1] [2] [3] [4] [5]
# generate an empty list
filtered_dataset = []
© Faculty of Management
for loop with range function
for loop with range() function
1
for num in range(1, 10, 2): 3
print(num) 5
7
9
Start Stop Step
(default=0) (default =1)
range() function: 2 Parameters
Accessing elements by index.
website_list=['google','youtube','instagram']
print(website_list[0])
for i in range(0, 3):
print(website_list[1])
print(website_list[i])
print(website_list[2])
range(A,B)
Creates a range of integers starting from A and increasing by 1 (=default
value), and the range ends at B-1.
range() function: 1 Parameter
Accessing elements by index
website_list=['google','youtube','instagram']
3
for i in range(0, 3): for i in range(len(website_list)):
print(website_list[i]) print(website_list[i])
range(B)
Creates a range of integers starting from
0 (=default value) and increasing by 1
(=default value), and the range ends at
B-1.
range() function: 1 Parameter (cont.)
Repeat a block of code for a specific number of times.
Hello!
for num in range(5): Hello!
#code block to be repeated Hello!
print("Hello!") Hello!
Hello!
Desired number
of repetitions
Summary
• The for loop is a control flow statement used to repeat a code block.
• It provides a convenient and concise syntax for iterating over
elements in a sequence, such as lists, tuples, or strings.
• The loop variable used in the for loop automatically takes on the
value of each element in the sequence, eliminating the need for
manual indexing or iteration control.
• The for loop is often used with the range() function to generate a
sequence of numbers over which the loop iterates.
• The range() function can accept parameters to specify the
generated sequence’s starting point, ending point, and step size,
providing flexibility in controlling the range of values.