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

DigitalSkills&Python Chapter4

This document provides an overview of Python's list data structure, including its creation, indexing, slicing, and various operations such as concatenation and duplication. It explains how to manipulate lists using methods like append, insert, extend, and remove, along with examples for clarity. Additionally, it covers the use of predefined functions like len() and range() to work with lists effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DigitalSkills&Python Chapter4

This document provides an overview of Python's list data structure, including its creation, indexing, slicing, and various operations such as concatenation and duplication. It explains how to manipulate lists using methods like append, insert, extend, and remove, along with examples for clarity. Additionally, it covers the use of predefined functions like len() and range() to work with lists effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Digital Skills and Python Programming

Chapter 4
Python Overview and Basic Syntax:
Python Data Structures: List, Tuple &
Dictionary
Pr. Mehdia AJANA
Email: [email protected]
PYTHON Lists
A list is a data structure used to store multiple
First steps items in a single variable.
Lists are created using square brackets [ and ]:
[ ] : empty list

[1, 2, 3, 4] : list of integers from 1 to 4


Data Structures
[ ‘a’, ‘b’, ‘c’] : list of letters a, b and c
Lists
["Mercury", "Venus", "Earth", "Mars", "Jupiter",
"Saturn", "Uranus", "Neptune"] : list of strings
representing the planets of our solar system.

2
Pr. Mehdia AJANA
Examples of Lists :
PYTHON >>> # Assigning a list to the variable "precious_stones"

First steps >>>precious_stones = ["Sapphire", 'Diamond', "Ruby",


'Emerald']
>>> # Querying Python to know the value of "precious_stones"
>>> precious_stones

>>> # When displaying a list, Python returns it as it was entered or


Data Structures assigned.
['Sapphire', 'Diamond', 'Ruby', 'Emerald']

Lists >>> #List of floating-point numbers.


>>> grades = [12.0, 16.5, 14.75, 10.25]

In Python, lists can contain values of different types (for example,


integers and strings), giving them great flexibility.

>>> # Mixed list containing strings and numbers.


>>> mixed_list = ['Sapphire', 12, 'Ruby', 10.25]
Pr. Mehdia AJANA 3
PYTHON List Indexing (Array Principle)
• List items are ordered: they have a defined order,
First steps and that order will not change.
• If you add new items to a list, the new items will be
placed at the end of the list.
• The list is mutable: we can change, add, and remove
items in a list after it has been created.
• In a list, each item is identified by its position= index,
Data Structures the first item has index [0], the second item has index
[1] etc.
Lists • The index starts at « 0 » and ends at « n-1 » (where n
is the number of elements in the list)
• Lists allow duplicate values: Since lists are indexed,
lists can have items with the same value
Example :
Index : 0 1 2 3
List : ["Sapphire", 'Diamond', "Ruby", 'Emerald']

Pr. Mehdia AJANA 4


PYTHON Example :
>>> # Assigning a list to the variable "precious_stones“
First steps
>>> precious_stones = ['Sapphire', 'Diamond', 'Ruby',
'Emerald']

>>> # Accessing elements by their index

>>> precious_stones[0] # Output: Sapphire


Data Structures
>>> precious_stones[1] # Output: Diamond

Lists >>> precious_stones[2] # Output: Ruby

>>> precious_stones[3] # Output: Emerald

>>> precious_stones[4] # This will cause an error


IndexError: list index out of range Since there is no
element at index 4,
we get an error
message.
Pr. Mehdia AJANA 5
Negative Indexing
PYTHON Negative indices start counting from the end of the list.
First steps Even if we do not know the length of the list, we can
access the last element, which has the index : -1.

Example :
list : ['A','C','D','E','F','G','H','I','K','L']
Positive Index : 0 1 2 3 4 5 6 7 8 9
Data Structures Negative Index : -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Lists >>> list = ['A','C','D','E','F','G','H','I','K','L']


>>>list[-7]
‘E’
>>>list[-1]
‘L’
>>>list[9]
‘L’
Pr. Mehdia AJANA 6
PYTHON List Slicing
Range of indices: You can specify a range of indices by
First steps specifying where to start and where to end the range.
For the range [m:n]: The search will start at index m
(included) and end at index n (not included).
• By leaving out the start value, the range will start at
the first item.
• By leaving out the end value, the range will go on to
Data Structures the end of the list.
Examples :
>>> precious_stones = ['Sapphire', 'Diamond', 'Ruby',
Lists 'Emerald']

>>>#Displaying the entire slice from the beginning to the


end
>>> precious_stones[ : ] #This is equivalent to
requesting precious_stones

['Sapphire', 'Diamond', 'Ruby', 'Emerald']

Pr. Mehdia AJANA 7


PYTHON Examples (continued) :
precious_stones = ['Sapphire', 'Diamond', 'Ruby',
First steps 'Emerald']
>>> #Slice from the beginning to a given position (here =
2 excluded)
>>> precious_stones[ :2]
['Sapphire', 'Diamond']
>>> #Slice from index 2 to the last index (3) which is
Data Structures excluded.
>>> precious_stones[2:3]
['Ruby']
Lists
>>> #Slice from index 2 to the last index (-1) which is
excluded
>>> precious_stones[2 :-1]
['Ruby']
>>> #Slice from index (-4) to index (-2) excluded
>>> precious_stones [-4 :-2]
['Sapphire', 'Diamond’]
Pr. Mehdia AJANA 8
List slicing with a step
PYTHON [start:end:step]: This allows you to create a slice of a list
First steps while specifying the « step »
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>># Traversing the list from the start to the end with a
step = 1
>>> mylist[ ::1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Data Structures >>># Traversing the list from the start to the end with a
step =3
>>> mylist[ ::3]
Lists [0, 3, 6, 9]
>>># Traversing from the element at index 1 to the end
with a step=2
>>> mylist[1: :2]
[1, 3, 5, 7, 9]
>>># Traversing from the element at index 2 to the
element at index 6 with a step = 1
>>> mylist[2:7:1]
[2, 3, 4, 5, 6]
Pr. Mehdia AJANA 9
Inserting Values with List Slicing
PYTHON
List slicing allows you to extract and also add or
First steps modify portions of a list using the list[start:stop]
syntax
start: The index to begin slicing (inclusive)
stop: The index where slicing ends (exclusive)

Data Structures Inserting Elements using Slicing


When the start and stop are the same, you can
Lists insert elements into the list without removing
anything:
my_list = [1, 2, 4, 5]
# Insert 3 at index 2
my_list[2:2] = [3]
print(my_list) # Output: [1, 2, 3, 4, 5]

Pr. Mehdia AJANA 10


Updating Values with List Slicing
PYTHON You can replace multiple elements at once
First steps using slicing with different start and stop
indices.
Example:
my_list = [1, 2, 3, 4, 5]

Data Structures # Replace elements at indices 1 to 3


my_list[1:4] = [10, 11]
Lists
print(my_list)
# Output: [1, 10, 11, 5]

The slice my_list[1:4] selects elements [2, 3, 4]


and replaces them with [10, 11].

Pr. Mehdia AJANA 11


Lists Operations
PYTHON Concatenation with the "+" Operator
First steps Example 1:
>>> precious_stones_1 = ['Sapphire', 'Diamond']
>>> precious_stones_2 = ['Ruby', 'Emerald']

>>> precious_stones_1 + precious_stones_2 # Concatenation

Data Structures ['Sapphire', 'Diamond', 'Ruby', 'Emerald']


Example 2:

Lists >>> Stock_Value1 = [25, 27, 28]


>>> Stock_Value2 = [40, 35, 38]
>>> Stock_Value3 = [12, 18, 10]

>>> Stock_VALUES = Stock_Value1 + Stock_Value2 +


Stock_Value3
>>> Stock_VALUES # You can also use print(Stock_VALUES)
[25, 27, 28, 40, 35, 38, 12, 18, 10]
Pr. Mehdia AJANA 12
PYTHON Lists Operations
Duplication with the « * » Operator
First steps Example 1:
>>> rolling_stones = ['Rolling', 'Stones']
>>> # Duplicating the list rolling_stones 3 times
>>> rolling_stones * 3
Data Structures [‘Rolling’, ‘Stones‘, ‘Rolling’, ‘Stones‘, ‘Rolling’, ‘Stones']

Lists Example 2:
>>> IP = [192, 162, 1, 1]
>>> # Duplicating the list IP 2 times
>>> IP2 = IP * 2
>>> IP2
[192, 162, 1, 1, 192, 162, 1, 1]
Pr. Mehdia AJANA 13
Lists Operations
PYTHON Adding Elements with « + »
First steps >>> Grades = [] # Initialize an empty list with []
>>> Grades
[]
>>># Add an element by concatenation
Data Structures >>> Grades = Grades + [15]
>>>#Concatenate the empty list [] with the list [15]
Lists >>> Grades #Querying Python for the value of Grades?
[15]
>>># Similarly adding a second element
>>> Grades = Grades + [-5]
>>> Grades
[15, -5]
Pr. Mehdia AJANA 14
PYTHON Lists Operations
Check if Item Exists
First steps To determine if a specified item is present in a list
use the in keyword.

Example:
Check if "apple" is present in the list:
Data Structures
list1 = ["apple", "banana", "cherry"]
Lists if "apple" in list1:

print("Yes, 'apple' is in the fruits’ list")

Yes, 'apple' is in the fruits list

Pr. Mehdia AJANA 15


Predefined Functions for Lists
PYTHON
Functions: range() and list()
First steps  The range() function generates a sequence of
integers based on the model range([start,] stop[,
step]).
 The list() function is used to generate a list from
this range and it is called a list constuctor.
Data Structures Examples :
>>># List from 0 to 15 (excluded)
Lists >>> list(range(15))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]

>>> # List of 5 integers from 5 to 9


>>> list(range(5,10))
[5, 6, 7, 8, 9]
Pr. Mehdia AJANA 16
Predefined Functions for Lists
PYTHON Examples (continued) :
First steps
>>># List from 0 to 250 (excluded) with a step of 25
>>> list(range(0,250, 25))
[0, 25, 50, 75, 100, 125, 150, 175, 200, 225]
Data Structures
# List of integers from 200 to 500 (excluded) with a
step of 100
Lists
>>> list(range(200,500,100))
[200, 300, 400]

Pr. Mehdia AJANA 17


Predefined Functions for Lists
PYTHON Functions: len() returns the length of a list.
First steps >>>precious_stones = ["Sapphire", 'Diamond', "Ruby",
'Emerald']
>>># The list precious_stones contains 4 elements
>>> len (precious_stones)
4
>>>#The statement list(range(0, 300, 100)) returns the
Data Structures list [0, 100, 200], which has 3 elements
>>>len(list(range(0,300,100)))
Lists 3

>>># [5, 6, 7, 8, 9]
>>> len(list(range(5,10)))
5
>>># [200, 300, 400, 500, 600, 700, 800, 900]
>>> len(list(range(200,1000,100)))
8
Pr. Mehdia AJANA 18
Predefined Functions for Lists
PYTHON
First steps The append() Method allows you to add an element to
the end of a list:

>>> Interval = [] >>> Modules = []


>>> Interval.append(-1) >>> Module.append(“Data
>>> Interval Analysis”)
Data Structures [-1] >>> Module
>>> Interval.append(1) [“Data Analysis”]
Lists >>> Interval >>> Module.append(“Algebra”)
[-1, 1] >>> Module
[“Data Analysis”, “Algebra”]
>>> Module.append(“Algorithms”)
>>> Module
[“Data Analysis”, “Algebra”,
“Algorithms”]

Pr. Mehdia AJANA 19


Predefined Functions for Lists
PYTHON
The insert() Method
First steps  To insert a new list item, without replacing any
of the existing values, we can use the insert()
method.
 The insert() method inserts an item at the
specified index
Data Structures Example :
Insert "watermelon" as the third item:
Lists
>>> list1 = ["apple", "banana", "cherry"]
>>> list1.insert(2, "watermelon")
>>> print(list1)
['apple', 'banana', 'watermelon', 'cherry']

Pr. Mehdia AJANA 20


Predefined Functions for Lists
PYTHON The extend() Method
First steps  To append elements from another list to the
current list, use the extend() method.
Example :
Add the elements of tropical to fruits:
Data Structures >>> fruits= ["apple", "banana", "cherry"]
>>> tropical = ["mango", "pineapple",
Lists "papaya"]
>>> fruits.extend(tropical)
>>> print(fruits)
['apple', 'banana', 'cherry', 'mango', 'pineapple',
'papaya']

Pr. Mehdia AJANA 21


Predefined Functions for Lists
PYTHON Remove a Specified Item:
First steps  The remove() method removes the specified item.
Example :
>>> fruits = ["apple", "banana", "cherry"]
>>> fruits.remove("banana")
Data Structures >>> print(fruits)
['apple', 'cherry']
Lists  If there are more than one item with the specified
value, the remove() method removes the first
occurrence:
>>> fruits = ["apple", "banana", "cherry",
"banana", "kiwi"]
>>> fruits.remove("banana")
>>> print(fruits)
['apple', 'cherry', 'banana', 'kiwi']
Pr. Mehdia AJANA 22
Predefined Functions for Lists
PYTHON
Remove a Specified Index:
First steps  The pop() method removes the item at a specified
index, and returns it.
Example :
Remove the second item:

Data Structures >>> fruits = ["apple", "banana", "cherry"]


>>> x= fruits.pop(1)
Lists >>> print(x)
>>> print(fruits)
banana
['apple', 'cherry']
 If you do not specify the index, the pop() method
removes the last item.

Pr. Mehdia AJANA 23


Predefined Functions for Lists
PYTHON Remove a Specified Index:
First steps  The del keyword also removes a specified index:
Example :
Remove the first item:
>>> fruits = ["apple", "banana", "cherry"]

Data Structures >>> del fruits[0]


>>> print(fruits)
Lists ['banana', 'cherry']
 The del keyword can also delete the list completely.
Example :
>>> fruits = ["apple", "banana", "cherry"]
>>> del fruits
>>> print(fruits) #this will cause an error because
you have succsesfully deleted “fruits“ list.
24
Predefined Functions for Lists
PYTHON
Clear the List:
First steps  The clear() method empties the list.
 The list still exists, but it has no content
Example :
Clear the list content:
Data Structures >>> fruits = ["apple", "banana", "cherry"]
>>> fruits.clear()
Lists
>>> print(fruits)
[]

Pr. Mehdia AJANA 25


Predefined Functions for Lists
PYTHON
List Count Method:
First steps  The count() method returns the number of
elements with the specified value.
Example :
Return the number of times the value “apple"
appears in the fruits list:
Data Structures
>>> fruits = ['apple', 'banana', 'apple', 'cherry']
Lists >>> x = fruits.count("apple")
>>> print(x)
2

Pr. Mehdia AJANA 26


Exercises:
PYTHON
1. What is the output of the following code?
First steps my_list = [10, 20, 30, 40, 50]
print(my_list[:4:2])
2. Given the following code, what does
my_list[::-1] return?
Data Structures my_list = [1, 2, 3, 4, 5]
print(my_list[::-1])
Lists 3. Which of the following methods is used to
add an element to the end of a list?
a) append()
b) extend()
c) insert()
d) add()
Pr. Mehdia AJANA 27
Solution:
PYTHON
1. What is the output of the following code?
First steps my_list = [10, 20, 30, 40, 50]
print(my_list[:4:2]) # [10, 30]
2. Given the following code, what does
my_list[::-1] return?
Data Structures my_list = [1, 2, 3, 4, 5]
print(my_list[::-1]) # [5, 4, 3, 2, 1]
Lists 3. Which of the following methods is used to
add an element to the end of a list?
a) append()
b) extend()
c) insert()
d) add()
Pr. Mehdia AJANA 28
List of Lists
PYTHON We will create our main list « precious_stones »
First steps from individual stone lists :
>>> stone1 = ["Diamond", 'White']
>>> stone2 = ["Emerald", 'Green']
>>> stone3 = ["Ruby", 'Red']
>>> stone4 = ["Sapphire", 'Blue']
Data Structures
precious_stones = [stone1, stone2, stone3, stone4]
Lists
Here is the result that Python returns:
>>> precious_stones

[['Diamond', 'White'], ['Emerald', 'Green'],


['Ruby', 'Red'], ['Sapphire', 'Blue']]

Pr. Mehdia AJANA 29


List of Lists
PYTHON Accessing Elements of Our Main List
First steps >>> precious_stones
[['Diamond', 'White'], ['Emerald', 'Green'], ['Ruby',
'Red'], ['Sapphire', 'Blue']]
If we want to access the elements of our main list :
>>> precious_stones[2]
# Python displays the element at index 2
Data Structures
['Ruby', 'Red']
This element contains a sublist with 2 elements, so we
Lists will use double indexing:
>>> precious_stones[2][0]
# Here is the 1st element at index 0
'Ruby'
>>> precious_stones[2][1]
# Here is the 1st element at index 1
'Red'
Pr. Mehdia AJANA 30
Loop Through a List using a for Loop
PYTHON
You can loop through the list items by using a
First steps for loop:
Example :
Print all items in the list, one by one:
>>> fruits = ["apple", "banana", "cherry"]
Data Structures
>>> for x in fruits:
Lists print(x)
apple
banana
cherry

Pr. Mehdia AJANA 31


Loop Through a List using the Index
PYTHON Numbers
First steps  You can also loop through the list items by
referring to their index number using the range()
and len() functions.
Example :

Data Structures Print all items in the list, one by one:


>>> fruits = ["apple", "banana", "cherry"]
Lists >>> for i in range(len(fruits)):
print(fruits[i])
apple
banana
Cherry

Pr. Mehdia AJANA 32


Loop Through a List using a While Loop
PYTHON
 You can loop through the list items by using a
First steps while loop and the len() function.
Example :
Print all items in the list, one by one:
>>> fruits = ["apple", "banana", "cherry"]
Data Structures >>> i = 0
>>> while i < len(fruits):
Lists
print(fruits[i])
i=i+1
apple
banana
cherry
Pr. Mehdia AJANA 33
Sort List Alphanumerically
PYTHON
 Lists have a sort() method that arranges the
First steps elements in alphabetical or numerical order. By
default, it sorts in ascending order.

Example 1 :
Sort the list alphabetically:
Data Structures
>>> fruits = ["orange", "mango", "kiwi",
"pineapple", "banana"]
Lists
>>> fruits.sort()
>>>print(fruits)

['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Pr. Mehdia AJANA 34


Sort List Alphanumerically
PYTHON
 Lists have a sort() method that arranges the
First steps elements in alphabetical or numerical order. By
default, it sorts in ascending order.

Example 2 :
Sort the list numerically:
Data Structures
>>> thislist = [100, 50, 65, 82, 23]
Lists >>> thislist.sort()
>>>print(thislist)
[23, 50, 65, 82, 100]

Pr. Mehdia AJANA 35


Sort Descending
PYTHON  To sort descending, use the keyword argument
First steps reverse = True
Example :
Sort the list descending:
>>> thislist = ["orange", "mango", "kiwi",
Data Structures "pineapple", "banana"]
>>> thislist.sort(reverse = True)
Lists >>>print(thislist)

['pineapple', 'orange', 'mango', 'kiwi', 'banana']

Pr. Mehdia AJANA 36


Reverse Order
PYTHON  The reverse() method reverses the current order
First steps of the elements.
Example :
Reverse the order of the list items:
>>> thislist = ["banana", "Orange", "Kiwi",
"cherry"]
Data Structures
>>> thislist.reverse()
Lists >>>print(thislist)

['cherry', 'Kiwi', 'Orange', 'banana']

Pr. Mehdia AJANA 37


Find the Position in a List
PYTHON  The index() method is used to find the position
First steps (index) of the first occurrence of a specified value
within the list. It raises a ValueError if the value is
not found in the list.
Example :
my_list = [10, 20, 30, 40, 50, 30]
Data Structures # Finds the index of the first occurrence
of 30
Lists
index_of_30 = my_list.index(30)
print(index_of_30) # Output: 2
print(my_list.index(60))
# ValueError: 60 is not in list
Note: Unlike strings, Python lists do not have a
find() method
Pr. Mehdia AJANA 38
Copy a List
PYTHON  You cannot copy a list simply by typing list2 =
First steps list1, because: in this case changes made in list1
will automatically also be made in list2.
 You can use the built-in List method copy() to
copy a list
 Another way to make a copy is to use the built-in
method list()
Data Structures
 You can also make a copy of a list by using the :
(slice) operator
Lists
Examples :
>>> fruits = ["apple", "banana", "cherry"]
>>> mylist1 = fruits.copy()
>>> mylist2 = list(fruits)
>>> mylist3 = fruits[:]

Pr. Mehdia AJANA 39


List Comprehension
PYTHON  List comprehension offers a shorter syntax /
First steps compact way when you want to create a new list
based on the values of an existing list.
Example : using a for loop
To create a list of uppercase versions of some fruit
names:
Data Structures fruits = ["apple", "banana", "cherry"]

Lists uppercase_fruits = []

for fruit in fruits:

uppercase_fruits.append(fruit.upper())

print(uppercase_fruits)

# Output: ['APPLE', 'BANANA', 'CHERRY']

Pr. Mehdia AJANA 40


List Comprehension
PYTHON Example : using List Comprehension
First steps The same result could be achieved with list
comprehension:
fruits = ["apple", "banana", "cherry"]
uppercase_fruits = [fruit.upper() for fruit in
fruits]
Data Structures print(uppercase_fruits)
# Output: ['APPLE', 'BANANA', 'CHERRY']
Lists
 List comprehension allows us to write this in a
single line
 Syntax: [expression for item in list]
 For each fruit in the fruits list, we apply the
.upper() method and store the result directly in the
new list “uppercase_fruits”.

Pr. Mehdia AJANA 41


PYTHON Conditionals in List Comprehension
 List comprehensions can use conditional
First steps statements: if…else to filter existing lists.
 Adding conditions to list comprehension helps
filter elements based on criteria, making the
process more efficient and readable.
Syntax of List Comprehension:
Data Structures
[expression for item in list if condition == True]

Lists
 for every item in list, execute the expression if
the condition is True
 Note: The if statement in list comprehension is
optional

Pr. Mehdia AJANA 42


Conditionals in List Comprehension
PYTHON Example :
First steps fruits = ["apple", "banana", "cherry",
"apricot"]
uppercase_a_fruits = [fruit.upper() for
fruit in fruits if fruit.startswith('a')]
Data Structures print(uppercase_a_fruits)
# Output: ['APPLE', 'APRICOT']
Lists
 The condition if fruit.startswith('a') is added at
the end of the list comprehension.
 It adds only fruits that start with 'a' and
converts them to uppercase to the
“uppercase_a_fruits” list, keeping the code
concise.

Pr. Mehdia AJANA 43


Conditionals in List Comprehension
PYTHON Another Example :
First steps  The expression can also contain conditions,
not like a filter, but as a way to manipulate the
outcome:
Return "orange" instead of "banana":
Data Structures fruits = ["apple", "banana", "cherry", "kiwi",
"mango"]
Lists newlist = [fruit if fruit != "banana" else
"orange" for fruit in fruits]

# Output: ['apple', 'orange', 'cherry', 'kiwi',


'mango']

Pr. Mehdia AJANA 44


Exercises:
PYTHON
1. What will be the output of the following
First steps Python code?
my_string = "hello world"

k = [(i.upper(), len(i)) for i in my_string]


Data Structures print(k)

Lists

Pr. Mehdia AJANA 45


Solution:
PYTHON
1. What will be the output of the following
First steps Python code?
my_string = "hello world"
k = [(i.upper(), len(i)) for i in my_string]
Data Structures print(k)
[(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1), (‘ ‘, 1),
Lists (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1), (‘D’, 1)]

Pr. Mehdia AJANA 46


Exercises:
PYTHON
2. What will be the output of the following
First steps Python code?

print([i+j for i in "abc" for j in "def"])

Data Structures

Lists

Pr. Mehdia AJANA 47


Solution:
PYTHON
2. What will be the output of the following
First steps Python code?

print([i+j for i in "abc" for j in "def"])


[‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]
Data Structures

Lists

Pr. Mehdia AJANA 48


Exercises:
PYTHON
3. What will the following list comprehension
First steps output?

numbers = [10, 15, 20, 25, 30, 35, 40]

result = [n * 2 for n in numbers if n % 2 == 0 and n


> 20]
Data Structures
print(result)

Lists a) [20, 30, 40]

b) [40, 60]

c) [40, 60, 80]

d) [60, 80]

Pr. Mehdia AJANA 49


Solution:
PYTHON
3. What will the following list comprehension
First steps output?

numbers = [10, 15, 20, 25, 30, 35, 40]

result = [n * 2 for n in numbers if n % 2 == 0 and n


> 20]
Data Structures
print(result)

Lists a) [20, 30, 40]

b) [40, 60]

c) [40, 60, 80]

d) [60, 80]

Pr. Mehdia AJANA 50


Summary of List Methods
PYTHON
Method Description
First steps append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
Returns the number of elements with the specified
count() value
Add the elements of a list (or any iterable), to the end
extend() of the current list
Data Structures Returns the index of the first element with the
index() specified value

Lists insert() Adds an element at the specified position


pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
Arrange the elements of the list in alphanumerical
sort() ascending order
For more examples about List methods you can check the
following link: https://www.geeksforgeeks.org/list-methods-
python/ Pr. Mehdia AJANA 51
PYTHON Definition & Syntax
• Tuples are used to store multiple items in a single
First steps variable.
• Tuple is one of 4 built-in data types in Python
used to store collections of data, the other 3 are
List, Dictionary, and Set, all with different
qualities and usage.
Data Structures • A tuple is a collection which is ordered and
unchangeable/immutable.
• Tuples are written with parentheses ( ).
Tuple • A tuple is a collection of elements separated by
commas ( , ).
Example:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
Pr. Mehdia AJANA 52
Tuple Items
PYTHON Tuple items are ordered, unchangeable, and allow
duplicate values.
First steps Tuple items are indexed, the first item has index [0],
the second item has index [1] etc.
Ordered
Tuples are ordered: it means that the items have a
defined order, and that order will not change.
Unchangeable
Data Structures
Tuples are immutable: we cannot change, add or
remove items after the tuple has been created.
Tuple Allow Duplicates
Since tuples are indexed, they can have items with
the same value:
>>> thistuple = ("apple", "banana", "cherry",
"apple", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')

Pr. Mehdia AJANA 53


PYTHON Tuple Items
To determine how many items a tuple has, we can
First steps use the len() function:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(len(thistuple))
3
To create a tuple with only one item, you have to
Data Structures add a comma after the item, otherwise Python will
not recognize it as a tuple:
Tuple >>> thistuple = ("apple",)
>>> print(type(thistuple))
<class 'tuple'>
#NOT a tuple
>>> thistuple = ("apple")
>>> print(type(thistuple))
<class 'str'>
Pr. Mehdia AJANA 54
PYTHON Tuple Items
Tuple items can be of any data type:
First steps Example:
String, int and boolean data types:
>>> tuple1 = ("apple", "banana", "cherry")
>>> tuple2 = (1, 5, 7, 9, 3)
>>> tuple3 = (True, False, False)
Data Structures

Tuple A tuple can also contain different data types:


Example:
A tuple with strings, integers and boolean
values:

>>> tuple1 = ("abc", 34, True, 40, "male")

Pr. Mehdia AJANA 55


Access Tuple Items
PYTHON You can access tuple items by referring to the index
number, inside square brackets []: we proceed the
First steps same way as for lists and strings:
>>> tuple1 = ('a', 'b', 'c', 'd', 'e')
To display a value:
>>> tuple1[0]
‘a’
>>> tuple1[2]
Data Structures ‘c’
To display all the values in the tuple, we will write :
Tuple >>> for T in tuple:
... print (T)
...
‘a’ As with lists and strings, you
‘b’ can use the "in" keyword to
‘c’
check if an element is in a
‘d’
‘e’ tuple
Pr. Mehdia AJANA 56
PYTHON Access Tuple Items
>>> for T in tupl1:
First steps ... print (T, end=" ->")

a->b->c->d->e->

Data Structures By adding « end » followed by a separator,


Python understands that it should not move to
Tuple the next line and that the values printed by
print() should be separated by the specified
indicator, represented here by « -> ».

Pr. Mehdia AJANA 57


PYTHON Access Tuple Items
Negative Indexing
First steps • Tuples, like lists, can use negative indexing.
• Negative indexing means start from the end.
• Negative indexing starts from -1 for the last
item, -2 for the second last, and so on.
Example:
Data Structures
>>> tuple1 = ('a', 'b', 'c', 'd', 'e')
Tuple
>>> tuple1[-1]
'e'
>>> tuple1[-2]
'd'

Pr. Mehdia AJANA 58


PYTHON Access Tuple Items
Range of Indices
First steps • You can specify a range of indices by
specifying where to start and where to end
the range.
• When specifying a range, the returned value
will be a new tuple with the specified items.
Data Structures Example:
Tuple >>> fruitstuple =
("apple", "banana", "cherry", "orange", "kiwi
", "melon", "mango")
>>> print(fruitstuple[2:5])

('cherry', 'orange', 'kiwi')


Pr. Mehdia AJANA 59
Operations on Tuples
PYTHON
Python allows performing similar operations to
First steps lists, but tuples are immutable: they cannot be
modified once created; their elements cannot
be changed:

>>> tuple1 = ('a', 'b', 'c', 'd', 'e')


>>> print(tuple1[2:4])
('c', 'd')
Data Structures
Tuple >>> tuple1[1:3] = ('x', 'y') # *** error! ***

Error:
TypeError: 'tuple' object does not support item
assignment

Pr. Mehdia AJANA 60


Operations on Tuples
PYTHON Modifying a tuple by creating a new one:
First steps Instead, you can concatenate a new value with
the remaining part of the tuple to achieve the
effect of a modification:
To teplace ‘a’ with ‘Ali’
>>> tuple1 = ('a', 'b', 'c', 'd', 'e')

Data Structures
>>>tuple1 = (‘Ali',) + tuple1[1:]
Tuple
>>> print(tuple1)

(‘Ali', 'b', 'c', 'd', 'e')

Pr. Mehdia AJANA 61


Operations on Tuples
PYTHON Convert into a list:
First steps Since tuples are immutable, they do not have a
built-in append() method, you can convert it
into a list, add your item(s), and convert it back
into a tuple:

thistuple = ("apple", "banana", "cherry")


Data Structures y = list(thistuple)
Tuple y.append("orange")
thistuple = tuple(y)

('apple', 'banana', 'cherry', 'orange')

Pr. Mehdia AJANA 62


Operations on Tuples
PYTHON
Multiple Assignment
First steps >>> tup1, tup2 = ('a', 'b'), ('c', 'd', 'e')

Concatenation (join tuples)


>>> tup3=tup1 + tup2
>>> tup3
Data Structures ('a', 'b‘, 'c', 'd', 'e')
Tuple
Multiple Duplication (multiply tuples)
>>> tup4 = tup1*4
>>> tup4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

Number of Elements
>>> len(tup4)
8
Pr. Mehdia AJANA 63
Operations on Tuples
PYTHON Tuples are unchangeable, so you cannot remove
First steps their items.
Example: We want to delete an element from a
tuple using del:
>>> thistuple = ("apple", "banana", "cherry")
>>> del thistuple[2]

Python raises an error:


Data Structures
TypeError: 'tuple' object doesn't support item
Tuple deletion
However: The del keyword can delete the tuple
completely:
>>> thistuple = ("apple", "banana", "cherry")
>>> del thistuple
>>> print(thistuple)
#this will raise an error because the tuple no
longer exists
Pr. Mehdia AJANA 64
Operations on Tuples
PYTHON Also tuples do not have a remove() method:
First steps We can Convert the tuple into a list, remove the
item from the list and then convert it back into a
tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> y = list(thistuple)
>>> y.remove("apple")
>>> thistuple = tuple(y)
Data Structures >>> print(thistuple)
Tuple ('banana', 'cherry')

What is the point of tuples?


If the transmitted data should not be modified
accidentally within a program, tuples should be
used.
If you need a read-only version of a list or any data
sequence, use tuples to prevent modification.

Pr. Mehdia AJANA 65


Tuple Methods
PYTHON Python has two built-in methods that you can use
on tuples.
First steps Count():
Returns the number of times a specified value
occurs in a tuple:
>>> thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
>>> x = thistuple.count(5)
>>> print(x)
2
Data Structures Index():
Tuple Searches the tuple for the first occurrence of a
specified value and returns its position, raises an
error if the value is not found:
>>> thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
>>> x = thistuple.index(8)
>>> print(x)
3
Note: Unlike strings, Python tuples do not have a
find() method
Pr. Mehdia AJANA 66
PYTHON Unpacking a Tuple
When we create a tuple, we normally assign values to it.
First steps This is called "packing" a tuple:
fruits = ("apple", "banana", "cherry")
In Python, we are also allowed to extract the values
back into variables. This is called "unpacking":
(green, yellow, red) = fruits
# we can also use
Data Structures green, yellow, red = fruits apple
Tuple print(green) banana
print(yellow) cherry
print(red) <class 'str'>
print(type(green))

You can check more information about python tuples on:


https://www.geeksforgeeks.org/python-tuples/

Pr. Mehdia AJANA 67


PYTHON Python zip() Method
The zip() function in Python is used to combine two
First steps or more lists (or other iterables) into tuples.
It combines elements from the provided lists at the
same index.
If the lists are of unequal length, zip() stops when
the shortest list is exhausted.
Syntax:
Data Structures zip(iterable1, iterable2, ...)
Tuple Example:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']
zip1=zip(list1, list2) <zip object at
zip1List = list(zip1)
0x0000025727D7C100>
print(zip1)
[(1, 'a'), (2, 'b'), (3, 'c')]
print(zip1List)
Pr. Mehdia AJANA 68
Definition & Syntax
PYTHON • Dictionaries are used to store data values in
First steps key:value pairs.
• A dictionary is a collection which is ordered,
changeable and do not allow duplicates for the
keys.
• A dictionary can manage any type: numeric
values, strings, lists, tuples, dictionaries...
• Dictionaries are written with curly brackets {},
and have keys and values separated by a colon
Data Structures “:”, elements are separated by commas “,”:
Dictionary Example:
>>> thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
>>> print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Pr. Mehdia AJANA 69
Displaying the Keys and Values of a Dictionary:
PYTHON >>> Agenda = {“name": “Smith", “phone":
First steps “0611223344”}

keys(): Method used to display the keys of a


dictionary :
>>> for K in Agenda.keys():
... print (K)
Data Structures name
Dictionary phone

values(): Method used to display all the values of a


dictionary:
>>> for V in Agenda.values():
... print (V)
Smith
0611223344

Pr. Mehdia AJANA 70


Dictionary Methods:
PYTHON
>>> Agenda = {“name": “Karim", “phone":
First steps “0644332211”}

get(): Method used to display a value in a


dictionary:
>>> Agenda.get(“name")
Karim
Data Structures
items(): Method used to display the keys and
Dictionary values:
>>> for K,V in Agenda.items():
... print (K, V)

name Karim
phone 0644332211

Pr. Mehdia AJANA 71


PYTHON Dictionary Methods:
Warning:
First steps You cannot copy a dictionary simply by typing
CopyAgenda = Agenda, because: CopyAgenda will
only be a reference to Agenda, and changes made in
Agenda will automatically also be made in
CopyAgenda :
>>> Agenda = Agenda = {"name" : "Ali",
Data Structures "phone": "0699887766"}
Dictionary
>>> CopyAgenda = Agenda
>>> Agenda ["name"] = "Ahmed"
>>> Agenda
{'name': 'Ahmed', 'phone': '0699887766'}
>>> CopyAgenda
{'name': 'Ahmed', 'phone': '0699887766'}
Pr. Mehdia AJANA 72
PYTHON Dictionary Methods:
>>> Agenda = {"name" : "Ali", "phone":
First steps "0699887766"}
copy(): Method to create a copy of a dictionary :
>>> CopyAgenda = Agenda.copy()
>>> Agenda ["name"] = "Ahmed"
>>> Agenda
Data Structures
Dictionary {'name': 'Ahmed', 'phone': '0699887766'}
>>> CopyAgenda
{'name': 'Ali', 'phone': '0699887766'}
Another way to make a copy is to use the built-in
function dict():
>>> CopyAgenda= dict(Agenda)

Pr. Mehdia AJANA 73


PYTHON Dictionary Methods:
The fromkeys() method returns a dictionary with the
First steps specified keys and the specified value.
Syntax: dict.fromkeys(keys, value) :
Examples: Create a dictionary with 3 keys, all with
the value 0:
x = ('key1', 'key2', 'key3')
Data Structures y=0
Dictionary
thisdict = dict.fromkeys(x, y)
print(thisdict)
{'key1': 0, 'key2': 0, 'key3': 0}
If we don’t specify the value:
thisdict = dict.fromkeys(x)
{'key1': None, 'key2': None, 'key3': None}
Pr. Mehdia AJANA 74
PYTHON Update Dictionary:
Adding Items:
First steps Adding an item to the dictionary is done by using a
new index key and assigning a value to it:
>>> thisdict = {
"brand": "Ford",
"model": "Mustang",
Data Structures "year": 1964
}
Dictionary
>>> thisdict["color"] = "red"
>>> print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964,


'color': 'red'}

Pr. Mehdia AJANA 75


Update Dictionary:
PYTHON Adding Items: Update() Method
First steps We can also use the update() method to
add/update items from a given argument to the
dictionary: If the item does not exist, the item will
be added.

The argument must be a dictionary:


>>> thisdict = {
Data Structures
"brand": "Ford",
Dictionary "model": "Mustang",
"year": 1964
}
>>> thisdict.update({"color": "red"})
>>> print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964,


'color': 'red'}
Pr. Mehdia AJANA 76
PYTHON Update Dictionary:
Update() method:
First steps If the items exist, they will be updated:
>>> thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
Data Structures }
Dictionary >>> thisdict.update({"year": 2018})
>>> thisdict.update({"brand": "Opel",
"model": "Corsa"})
>>> print(thisdict)

{'brand': 'Opel', 'model': 'Corsa', 'year': 2018}

Pr. Mehdia AJANA 77


PYTHON Update Dictionary:
Change Values:
First steps We can also change the value of a specific item by
referring to its key name:
>>> thisdict = {
"brand": "Ford",
"model": "Mustang",
Data Structures "year": 1964
}
Dictionary
>>> thisdict["year"] = 2018
>>> print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Pr. Mehdia AJANA 78


Remove Dictionary Items:
PYTHON The pop() method removes the item with the specified
key name:
First steps >>> thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
>>> thisdict.pop("model")
Data Structures >>> print(thisdict)
Dictionary {'brand': 'Ford', 'year': 1964}
Note: If you don’t specify the key name the pop method
gives a TypeError: unbound method dict.pop() needs an
argument

The del keyword removes the item with the specified key
name:
>>> del thisdict["model"]
{'brand': 'Ford', 'year': 1964}
Pr. Mehdia AJANA 79
Remove Dictionary Items:
PYTHON The popitem() method removes the last inserted
First steps item (in versions before 3.7, a random item is
removed instead)
>>> thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Data Structures
>>> thisdict.popitem()
Dictionary >>> print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}

The clear() method empties the dictionary:


>>> thisdict.clear()
>>> print(thisdict)
{}

Pr. Mehdia AJANA 80


Loop Through a Dictionary:
PYTHON You can loop through a dictionary by using a for
First steps loop:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Data Structures
for x in thisdict:
Dictionary
print(x)
brand
model
year

Note: When looping through a dictionary, the


returned values are the keys of the dictionary.
Pr. Mehdia AJANA 81
Loop Through a Dictionary:
PYTHON You can also use the keys() method to return the
First steps keys of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Data Structures
Dictionary
for x in thisdict.keys():
print(x)

brand
model
year

Pr. Mehdia AJANA 82


Loop Through a Dictionary:
PYTHON To return the values you can use:
First steps thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Data Structures for x in thisdict:
Dictionary print(thisdict[x])
Ford
Mustang
1964
Or you can use the values() method:
for x in thisdict.values():
print(x)

Pr. Mehdia AJANA 83


Loop Through a Dictionary:
PYTHON You can loop through both keys and values, by using
First steps the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Data Structures
for x, y in thisdict.items():
Dictionary
print(x, y)

brand Ford
model Mustang
year 1964

Pr. Mehdia AJANA 84


Another Example
PYTHON
Unlike lists, it is not necessary to call a particular
First steps
method (such as append()) to add new elements to
a dictionary; you just need to create a new key-value
pair.
>>> traducteur = {}
>>> traducteur['intelligent'] ='smart'
Data Structures >>> traducteur['ville'] = 'city'
Dictionary >>> traducteur['Tanger'] ='Tangier'
>>> print(traducteur)

{'intelligent': 'smart', 'ville': 'city', 'Tanger': 'Tangier'}

To access an element, we use the keys:


>>> print(traducteur[‘ville'])
city

Pr. Mehdia AJANA 85


The keys() method returns the sequence of keys
PYTHON used in the dictionary.
First steps This sequence can be used as-is in expressions or,
converted into a list or tuple if needed, using the
corresponding built-in functions: list() and tuple():
>>> traducteur={"intelligent": "smart", "ville":
"city", "Tanger": "Tangier"}
>>> print(traducteur.keys())
Data Structures dict_keys(['intelligent', 'ville', 'Tanger'])
Dictionary >>> for k in traducteur.keys():
... print("key :", k, " --- value :", traducteur[k])
key : intelligent --- value : smart
key : ville --- value : city
key : Tanger --- value : Tangier
>>> list(traducteur .keys())
['intelligent', 'ville', 'Tanger']
Pr. Mehdia AJANA 86
>>> traducteur={"intelligent": "smart", "ville": "city",
PYTHON "Tanger": "Tangier"}
>>> tuple(traducteur .values())
First steps ('smart', 'city', 'Tangier')

#Displaying the keys


>>> for key in traducteur:
... print(key)
intelligent
ville
Tanger
Data Structures
#Displaying the values
Dictionary
>>> for key in traducteur:
... print(key, traducteur[key])
intelligent smart
ville city
Tanger Tangier

#Another way of displaying the values


>>> for key, val in traducteur.items():
... print(key, val)
Pr. Mehdia AJANA 87
Nested Dictionaries:
PYTHON A dictionary can contain dictionaries, this is called
nested dictionary:
First steps Example: Dictionary containing 3 dictionaries
myfamily = {
"child1" : {
"name" : “Ali",
"year" : 2004
},
Data Structures
"child2" : {
Dictionary "name" : “Ahmed",
"year" : 2007
},
"child3" : {
"name" : “Iyad",
"year" : 2011
}
}
Pr. Mehdia AJANA 88
Nested Dictionaries:
PYTHON You can also create three dictionaries, and then
create one dictionary that will contain the other
First steps three dictionaries:
child1 = {
"name" : “Ali",
"year" : 2004
}
child2 = {
"name" : “Ahmed",
Data Structures "year" : 2007
Dictionary }
child3 = {
"name" : “Iyad",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Pr. Mehdia AJANA 89
Access Items in Nested Dictionaries:
PYTHON To access items from a nested dictionary, you use the
name of the dictionaries, starting with the outer
First steps dictionary:
Example: Print the name of child 3:
myfamily = {
"child1" : {
"name" : “Ali",
"year" : 2004
},
Data Structures "child2" : {
"name" : “Ahmed",
Dictionary "year" : 2007
},
"child3" : {
"name" : “Iyad",
"year" : 2011
}
}
print(myfamily["child3"]["name"])
Iyad
Pr. Mehdia AJANA 90
Access Items in Nested Dictionaries:
PYTHON Example: Loop through the keys and values of all
First steps nested dictionaries:
myfamily = {
"child1" : { for x, obj in
"name" : “Ali", myfamily.items():
"year" : 2004 print(x)
}, for y in obj:
Data Structures "child2" : { print(y + ':', obj[y])
Dictionary "name" : “Ahmed",
child1
"year" : 2007 name: Ali
}, year: 2004
"child3" : { child2
"name" : “Iyad", name: Ahmed
year: 2007
"year" : 2011
child3
} name: Iyad
} year: 2011
Pr. Mehdia AJANA 91
Multiple Levels of Nesting:
PYTHON Multiple levels of nesting are possible in Python
First steps dictionaries
This allows us to store and organize data in a
hierarchical and flexible manner.
Ideal for representing real-world data like family
trees, organizational charts, or product catalogs…
Example: we add another dictionary for hobbies to
the inner child dictionary:
Data Structures myfamily = {
Dictionary "child1": {
"name": "Ali",
"year": 2004,
"hobbies": {
"sports": ["football", "basketball"],
"music": ["guitar", "piano"]
}
}
}
Pr. Mehdia AJANA 92
Summary of Dictionary Methods
PYTHON Method Description
First steps clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

Data Structures items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

Dictionary pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair


Updates the dictionary with the specified key-value
update() pairs

values() Returns a list of all the values in the dictionary

For more examples about Dictionary methods you can check the
following link: https://www.geeksforgeeks.org/python-dictionary-
methods/
Pr. Mehdia AJANA 93

You might also like