0% found this document useful (0 votes)
1 views49 pages

M02-Lecture Notes

The document provides an overview of data structures in Python, focusing on lists and dictionaries. It explains how to create, access, modify, and manipulate these structures, including operations such as adding, removing, and checking elements. Additionally, it covers the use of loops, specifically the 'for' statement, to iterate over sequences and utilizes the range function for generating sequences of numbers.

Uploaded by

Berly Brigith
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)
1 views49 pages

M02-Lecture Notes

The document provides an overview of data structures in Python, focusing on lists and dictionaries. It explains how to create, access, modify, and manipulate these structures, including operations such as adding, removing, and checking elements. Additionally, it covers the use of loops, specifically the 'for' statement, to iterate over sequences and utilizes the range function for generating sequences of numbers.

Uploaded by

Berly Brigith
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/ 49

Data Structure: Lists

© Faculty of Management
List
A type of data structure that deals with a list of data

Name Card Attendee Sheet


0 Marion • Index: The place to insert the
data of the list.
1 Ian
• Element: Individual data plugged
2 Elodie
into each index of the list
3 Jake
4 Allegra
Creating a List
A data structure that stores an ordered collection of items.
• A list begins with [ and ends with ]
• Items separated by comma
Square brackets define lists

list = ['a','b','c']

Commas separate elements


List Content
• You can create an empty list
my_list = []

• Lists can contain strings, integers, or floats


letters = ['a', 'b', 'c', 'd']
numbers = [2, 4, 5]

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

Names = ["Jim", "Michael", "Pam", "Dwight"]

Names [0] Names [1] Names [2] Names [3]

Names[-4] Names[-3] Names[-2] Names[-1]


Access a Range of Elements
To access a range of elements in a list, use slicing.
Slicing allows you to extract a subset of elements from a list based on a
specified range of indexes.
new_list=original_list[start:end:step]
• original_list is the list you want to slice.
• start represents the index of the first element to include in the slice.
• end represents the index of the element right before which the slice should stop
(exclusive).
• step (optional) specifies the interval between elements to include in the slice.
Examples: List Slicing
Names = ["Jim", "Michael", "Pam", "Dwight"]

print(Names[1:3]) # Output: ["Michael", "Pam"]


print(Names[:3]) # Output: ["Jim", "Michael", "Pam"]
print(Names[2:]) # Output: ["Pam", "Dwight"]
print(Names[::2]) # Output:["Jim", "Pam"]
Modify an Element
To modify an element in a list, you can assign a new value to the
specific index of the element.
Names = ["Jim", "Michael", "Pam", "Dwight"]
Names[1] = "Andrew" #Michael to Andrew
print(Names)

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

list_a= ['a', 'b', 'c'] a b c


list_a.pop(2) [0] [1] [2]
print(a)

#output a b
['a', 'b'] [0] [1]
Delete an Element (cont.)
remove (x)
Remove the first occurrence of a specified element from a list.

list_a= ['a', 'b', 'c', 'b'] a b c b


list_a.remove('b') [0] [1] [2] [3]
print(list_a)

#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}

Curly brackets define dictionary


Example: Dictionary

dict={key:value, • Keys in a dictionary must be unique.


key:value, • Values in a dictionary can be of any data type, such
key:value} as strings, numbers, lists, or other dictionaries.

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 = {}

# Add website names as keys and their blocking status as values


webpage_dict['google'] = False # Allowed
webpage_dict['youtube'] = True # Blocked
Access Values
To access values in a dictionary, use the key associated with the values.
# Access values based on keys
print(webpage_dict['google']) # Output: False
print(webpage_dict['youtube']) # Output: True
webpage_dict
value False True
key 'google' 'youtube'

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.

website_dict = { Check whether a specific key exists in the keys of


'google': False, the dictionary.
'youtube': True, 'google' in webpage_dict.keys()
'facebook': False
} keys() : returns a view object that contains all
the keys present in the dictionary.

webpage_dict.keys()

# Output: dict_keys(['google', 'youtube', 'facebook'])


Example: Program to Check Key in List
website_name = 'google'

# Checking if the website name is present in the keys of the dictionary


if website_name in website_dict.keys() :
# Checking the blocking status of the website
if website_dict[website_name]:
print(f"The website {website_name} is blocked.")
else:
print(f"The website {website_name} is not blocked.")
else:
print(f"The website {website_name} is not found in the dictionary.")
Summary
• A dictionary is an unordered collection of key-value pairs,
enclosed in curly brackets {}.
• The key acts as a unique identifier for each value in the dictionary.
• Values can be of any data type: strings, numbers, lists, or other
dictionaries.
• Accessing elements in a dictionary is done by using the key.
• Keys must be unique within a dictionary, and values can be
modified or updated.
For Loops

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

for item in sequence:


Code Block

• 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

print(website_list[0]) for website in website_list:


print(website_list[1]) print(website)
print(website_list[2])
Example: Print all elements
'google' 'youtube' 'Instagram'
[0] [1] [2]

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 = []

for price in price_list:


if price > 0:
filtered_dataset.append(price)
10 20 15 25
[0] [1] [2] [3]
print(filtered_dataset)
'for' Statement Steps
for each item
for item in sequence: in the sequence
Code Block
[Step 1] The loop starts by initializing the variable
with the first element from the sequence. Code Block
Last item in the
[Step 2] The code block inside the loop is False
executed. sequence?
[Step 3] After executing the code block, the loop
moves to the next element in the sequence, and True
the variable is updated with the value.
[Step 4] Step 2 and Step 3 are repeated until all
elements in the sequence have been iterated. End
Loops with Range Function

© Faculty of Management
for loop with range function
for loop with range() function

for variable in range(start,stop,step):


Code Block
Repeating a certain block of the code Generate a sequence of numbers
for num in range(5): for num in range(1, 10, 2):
Hello! 1
print("Hello!") print(num)
Hello! 3
Hello! 5
Hello! 7
Hello! 9
range () function
Generates a sequence of numbers and returns an iterable object that
represents a range of values.
range(start, stop, step )

• start(optional, default=0): The starting value of the sequence.


• stop(required): The exclusive ending value of the sequence.
• step(optional, default=1): The increment between each value in the sequence.
range() function: 3 Parameters
range(A, B, C)
• Creates a range of integers starting from A and increasing by C, and
the range ends at B-1.
Print the numbers from 0 to 4. 0
1
for num in range(0, 5, 1):
2
print(num)
3
4
Start Stop Step
(default=0) (default =1)
range() function: 3 Parameters (cont.)
Print the odd numbers from 1 to 9.

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.

You might also like