0% found this document useful (0 votes)
18 views186 pages

Python Programming Fundamentals Guide

Uploaded by

team03up
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)
18 views186 pages

Python Programming Fundamentals Guide

Uploaded by

team03up
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

Introduction

Goals of the course

● Understand the fundamentals of Python programming.


● Build problem-solving and coding skills.
● Work on real-world projects and applications.
Why Python

● Easy to learn and use


● Python has an active, supportive community
● Hundreds of Python libraries and frameworks
● Python is flexible
● Compatible with major platforms and systems
● Growing market demand (avg salary 135,000$).
Install Python

● Installation Link: [Link]


● to check if u have Python :
In your terminal type “python “ or “python --version”
Editors and IDEs

● PyCharm
○ Robust debugging tool
○ Error detection and fix-up suggestions
○ [Link]
● Jupyter
○ Good user interface
○ Combines code, text, and images
○ [Link]
● Spyder
○ Smart editing and debugging
○ Support for automatic code completion and splitting
● Google Colaboratory
○ No heavy file downloads
○ Runs on cloud
○ Updated in google drive
Python Syntax
What is Python?

• Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.


• It was created by Guido van Rossum, and released in 1991.
• Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of
program maintenance.

• It is used for:
o web development (server-side).
o software development.
o mathematics.
o system scripting.
Python Comments

• Comments starts with a #, and Python will ignore them:


#This is a comment
print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the rest of the line:
print("Hello, World!") #This is a comment
• A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:
#print("Hello, World!")
print("Cheers, Mate!")
Python Comments

• Multiline Comments : Python does not really have a syntax for multiline comments.
#This is a comment
#written in
#more than just one line
print("Hello, World!")

• Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables

• Variables are containers for storing data values.

• A variable is created the moment you first assign a value to it.


x = 5
y = "John"
print(x)
print(y)

• Variables do not need to be declared with any particular type, and can even change type after they
have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Python Variables

• If you want to specify the data type of a variable, this can be done with casting.

x = str(3) # x will be '3’


y = int(3) # y will be 3
z = float(3) # z will be 3.0

• You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))
Python Variables

• String variables can be declared either by using single or double quotes:

x = "John"
# is the same as
x = 'John'

• Variable names are case-sensitive.

a = 4
A = "Sally"
#A will not overwrite a
Python Variables

• Rules for Python variables:


o A variable name must start with a letter or the underscore character
o A variable name cannot start with a number
o A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
o Variable names are case-sensitive (age, Age and AGE are three different variables)
o A variable name cannot be any of the Python keywords.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Python Variables

Variable names with more than one word can be difficult to read.
• Camel Case 🡪 Each word, except the first, starts with a capital letter:
myVariableName = "John"

• Pascal Case 🡪 Each word starts with a capital letter:


MyVariableName = "John"

• Snake Case 🡪 Each word is separated by an underscore character:


my_variable_name = "John"
Python Variables

• Python allows you to assign values to multiple variables in one line:


x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Python Variables

• The Python print() function is often used to output variables.


• In the print() function, you output multiple variables, separated by a comma.
• You can also use the + operator to output multiple variables.
• For numbers, the + character works as a mathematical operator:
• In the print() function, when you try to combine a string and a number with the + operator, Python will
give you an error.
• The best way to output multiple variables in the print() function is to separate them with commas,
which even support different data types.
Data Types
Python Data Types

• Variables can store data of different types, and different types can do different things.
Python Data Types
• If you want to specify the data type, you can use the following constructor functions:

x = str("Hello World")
x = int(20)
x = float(20.5)
x = complex(1j)
x = list(("apple", "banana", "cherry"))
x = tuple(("apple", "banana", "cherry"))
x = range(6)
x = dict(name="John", age=36)
x = set(("apple", "banana", "cherry"))
x = frozenset(("apple", "banana", "cherry"))
x = bool(5)
x = bytes(5)
x = bytearray(5)
x = memoryview(bytes(5))
Python Numbers
• There are three numeric types in Python:

o int
o float
o complex

x = 1 # int
y = 2.8 # float
z = 1j # complex

print(type(x))
print(type(y))
print(type(z))
Python Numbers
• Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
Python Numbers
• Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))
Python Numbers
• You can convert from one type to another with the int() and float() methods:

x = 1 # int
y = 2.8 # float

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

print(a)
print(b)

print(type(a))
print(type(b))
Python Numbers
• Python does not have a random() function to make a random number, but Python has a built-in module
called random that can be used to make random numbers:

import random

#import the random module, and display a random number from 1 to 9:


print([Link](1, 10))
Python Numbers
• Casting in python is therefore done using constructor functions:

int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a
string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the
string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float
literals
Python Numbers

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Strings
Python Strings

• Strings in python are surrounded by either single quotation marks, or double quotation marks.
• You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
print("It's alright")
print("He is called 'Johnny’”)
print('He is called "Johnny"')
• You can assign a multiline string to a variable by using three quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Python Strings

• Python does not have a character data type, a single character is simply a string with a length of 1.
• Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])

• To get the length of a string, use the len() function.


a = "Hello, World!"
print(len(a))
Python Strings

• To check if a certain phrase or character is present in a string, we can use the keyword in.
txt = "The best things in life are free!"
print("free" in txt)

• To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
txt = "The best things in life are free!"
print("expensive" not in txt)
Slicing Strings

• You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon, to return a part of the string.
b = "Hello, World!"
print(b[2:5])

• By leaving out the start index, the range will start at the first character:
b = "Hello, World!"
print(b[:5])

• By leaving out the end index, the range will go to the end:
b = "Hello, World!"
print(b[2:])
Slicing Strings

• Use negative indexes to access the characters.


b = "Hello, World!"
print(b[-1])

• Use negative indexes to start the slice from the end of the string
b = "Hello, World!"
print(b[-5:-2])
Strings Methods

• The upper() method returns the string in upper case:


a = "Hello, World!"
print([Link]())

• The lower() method returns the string in lower case:


a = "Hello, World!"
print([Link]())
Strings Methods

• The strip() method removes any whitespace from the beginning or the end
a = " Hello, World! "
print([Link]()) # returns "Hello, World!“

• The replace() method replaces a string with another string:


a = "Hello, World!"
print([Link]("H", "J"))

The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation

• To concatenate, or combine, two strings you can use the + operator.

a = "Hello"
b = "World"
c = a + b
print(c)

• To add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)
F-Strings

• F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

• To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {}
as placeholders for variables and other operations.

age = 36
txt = f"My name is John, I am {age}"
print(txt)
F-Strings

• A placeholder can include a modifier to format the value.


• A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means
fixed point number with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
• A placeholder can contain Python code, like math operations:

txt = f"The price is {20 * 59} dollars"


print(txt)
Escape Character

• To insert characters that are illegal in a string, use an escape character.


• An escape character is a backslash \ followed by the character you want to insert.

txt = "We are the so-called "Vikings" from the north."

• To fix this problem, use the escape character \":

txt = "We are the so-called \"Vikings\" from the north."


Escape Character
Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value


Booleans & Operators
Python Booleans

• Booleans represent one of two values: True or False.


• When you compare two values, the expression is evaluated and Python returns the Boolean answer:

print(10 > 9)
print(10 == 9)
print(10 < 9)
Python Booleans

• The bool() function allows you to evaluate any value, and give you True or False in return,

print(bool("Hello"))
print(bool(15))

bool(False)
• Almost any value is evaluated to True if it has some sort of content.
bool(None)
• Any string is True, except empty strings. bool(0)
bool("")
• Any number is True, except 0.
bool(())
• Any list, tuple, set, and dictionary are True, except empty ones. bool([])
bool({})
Python Operators

• Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators (are used to compare binary numbers:)
Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements x < 5 and x < 10
are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location

Operator Description Example


is Returns True if both variables x is y
are the same object
is not Returns True if both variables x is not y
are not the same object
Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with x in y
the specified value is present in
the object
not in Returns True if a sequence with x not in y
the specified value is not
present in the object
Operator Precedence

Operator precedence describes the order in which operations are performed.

• Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))

• Multiplication * has higher precedence than addition +, and therefore multiplications are evaluated
before additions:

print(100 + 5 * 3)
Operator Precedence
Operator Description
The precedence order is () Parentheses
described in the table, starting
** Exponentiation
with the highest precedence at
the top. +x -x ~x Unary plus, unary minus, and bitwise NOT
* / // % Multiplication, division, floor division, and modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is Comparisons, identity, and membership operators
is not in not in
not Logical NOT
and AND
or OR
Operator Precedence

• If two operators have the same precedence, the expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefore we evaluate the expression from left to
right:

print(5 + 4 - 7 + 3)
Conditions
Python Conditions

Python supports the usual logical conditions from mathematics:


• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
if Statement

• An "if statement" is written by using the if keyword.

a = 33
b = 200
if b > a:
print("b is greater than a")

• Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.

• If statement, without indentation (will raise an error).


if Statement

• The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
if Statement

• The else keyword catches anything which isn't caught by the preceding conditions.

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If

• If you have only one statement to execute, you can put it on the same line as the if statement.

if a > b: print("a is greater than b")

• If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:

a = 2
b = 330
print("A") if a > b else print("B")
combine conditional statements

• The and keyword is a logical operator, and is used to combine conditional statements:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

• Test if a is greater than b, AND if c is greater than a.


combine conditional statements

• The or keyword is a logical operator, and is used to combine conditional statements:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

• Test if a is greater than b, OR if a is greater than c.


combine conditional statements

• The not keyword is a logical operator, and is used to reverse the result of the conditional statement:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

• Test if a is NOT greater than b.


The pass Statement

• if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.

a = 33
b = 200
if b > a:
pass
Conditions
Python Match Statement

• The match statement is used to perform different actions based on different conditions.
• Instead of writing many if..else statements, you can use the match statement.
• The match statement selects one of many code blocks to be executed.

match expression:
case x:
code block
case y:
code block
case z:
code block
Python Match Statement

• The match expression is evaluated once. day = 4


match day:
• The value of the expression is compared with the case 1:
values of each case. print("Monday")
case 2:
• If there is a match, the associated block of code print("Tuesday")
is executed. case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
Python Match Statement

• Use the underscore character _ as the last case value (Default Value) if you want a code block to
execute when there are not other matches:

day = 4
match day:
case 6:
print("Today is Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to the Weekend")

• The value _ will always match, so it is important to place it as the last case to make it behave as a
default case.
Python Match Statement

• Use the pipe character | as an or operator in the case evaluation to check for more than one value
match in one case.

day = 4
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a weekday")
case 6 | 7:
print("I love weekends!")
Python Match Statement

• You can add if statements in the case evaluation as an extra condition-check:

month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")
Exercises

• Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a
is less b return a is smaller than b, else a is equal to b.

• Generate a random number between 1 and 10. Ask the user to guess the number and print a message
based on whether they get it right or not.
Loops
Python While Loops

• With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
print(i)
i += 1

• Note: remember to increment i, or else the loop will continue forever.


Python While Loops

• With the break statement we can stop the loop even if the while condition is true:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

Exit the loop when i is 3.


Python While Loops

• With the continue statement we can stop the current iteration, and continue with the next:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Continue to the next iteration if i is 3.


Python While Loops

• With the else statement we can run a block of code once when the condition no longer is true:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Print a message once the condition is false.


Python For Loops

• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
• With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
• Even strings are iterable objects, they contain a sequence of characters.

for x in "banana":
print(x)
Python For Loops

• With the break statement we can stop the loop before it has looped through all the items:

fruitName = "watermelon"
for x in fruitName:
print(x)
if x == "m":
break

• Exit the loop when x is "m"


Python For Loops

• With the break statement we can stop the loop before it has looped through all the items:

fruitName = "watermelon"
for x in fruitName:
if x == "m":
break
print(x)

• Exit the loop when x is "m", but this time the break comes before the print:
Python For Loops

• With the continue statement we can stop the current iteration of the loop, and continue with the next:

fruitName = "watermelon"
for x in fruits:
if x == "m":
continue
print(x)
The range() Function

• To loop through a set of code a specified number of times, we can use the range() function,
• The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.

for x in range(6):
print(x)

• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() Function

• The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)

• The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
Else in For Loop

• The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

for x in range(6):
print(x)
else:
print("Finally finished!")

• The else block will NOT be executed if the loop is stopped by a break statement.

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the "outer loop“.

fruitName = "apple"
for x in range(3):
for y in fruitName:
print(x, y)
The pass Statement

• for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass
statement to avoid getting an error.

for x in [0, 1, 2]:


pass
Python programming
Data Structure – Lists
● Lists
● Tuples
● Sets
● Dictionaries
Why Data Structure? Why Lists?

If you have been asked to write the following program :


Create a program that asks the user to enter his grades in every subject. And then you need to do different
operations on this data that the user gave it to you.
Why Data Structure? Why Lists?

In more optimal way: you can use the for loop

But what if I asked you to print all the grades and the average.
What if I asked you to enter the grades for three students and print the same data (the name of the
student, his grades, and the average)
What is the List

• Lists are used to store multiple items in a single variable.


• List is a collection of an ordered sequence of items, and you can store the values of different data types.
• Strings are a sequence also, but only from Characters
Define a List

• You can define a list using the square brackets [ ].


• List items are ordered, changeable, and allow duplicate values.

# List with integer types


a = [30, 10, 20]
# List with string types
b = ["apple", "banana", "cherry", "strawberry"]
# List with mix types
c = [10, "Mercedes", 20]
# Empty List
d = []
Access Elements from List

• you can access elements from the list by using index values

lst = [10, 20, 30, ‘Apple’]


print(lst[0]) -> 10 0 1 2 3
print(lst[1]) -> 20
10 20 30 Apple
print(lst[2]) -> 30
print(lst[3]) -> ‘Apple’
Access Elements from List

• you can access elements from the list by using negative index values

lst = [10, 20, 30, ‘Apple’]


print(lst[-1]) -> ‘Apple’
print(lst[-2]) -> 30
print(lst[-3]) -> 20
print(lst[-4]) -> 10
0 1 2 3

10 20 30 Apple

-4 -3 -2 -1
Traversing a List

List Traversal is the process of visiting every item in a list, usually from the first item to the last item, and
executing some instruction on the accessed item.
• There is two ways to traverse a list.
o Direct Traversal : as a list is an order collection of items, the for statement can be used.
lst = [90, 'Skoda', 66, 'Kia', 'BMW’]
for item in lst:
print(item) 0 1 2 3 4

Output:
90 Skoda 66 Kia BMW
90
Skoda
-5 -4 -3 -2 -1
66
Kia
BMW
Traversing a List

o Location or index-based Traversal: using the index to access the items.


• for statement can be used to iterate over the index of the list using range() and len() methods.

lst = [90, 'Skoda', 66, 'Kia', 'BMW']


for i in range(len(lst)):
print(i, lst[i])
Output: 0 1 2 3 4

0 90
90 Skoda 66 Kia BMW
1 Skoda
2 66
-5 -4 -3 -2 -1
3 Kia
4 BMW
Traversing a List

Example 1: print the even number from a given list


lst = [22, 65, 73, 11, 4, 45, 77, 96, 44, 7, 34, 2]

Example 2: let the user enter the pass rate and print every grade if it is Passed or Failed
lst = [49, 65, 73, 82, 61, 45, 77, 96, 55, 75, 88, 92]
Adding Elements to a List

• You can add items to a list using the append() method, that add item to the end of the list.
lst = [96,80,70,92] 0 1 2 3 0 1 2 3 4
[Link](85)
print(lst) -> [96,80,70,92,85] 96 80 70 92 96 80 70 92 85

• If you need to add the item at particular index, use the insert() method.
lst = [96,80,70,92] 0 1 2 3 4
0 1 2 3
[Link](3,85)
print(lst) -> [96, 80, 70, 85, 92] 96 80 70 92 96 80 70 85 92

• If you want to add another list you can use the extend method.
lst = [96,80,70,92] 0 1 2 3 4 5
0 1 2 3
[Link]([85,88])
print(lst) -> [96, 80, 70, 92, 85, 88] 96 80 70 92 96 80 70 92 85 88
Adding Elements to a List

Example 3: Ask the user to enter the cars in the agency sorted by the manufactory date
Removing items from a list

• You can remove all the elements using the clear() method.
lst = [1, 5, 6, 8]
[Link]()
print(lst) -> []

• You can remove the first occurrence of an item using the remove() method.
lst = [1, 5, 6, 8, 5]
[Link](5) 0 1 2 3 4 0 1 2 3
print(lst) -> [1, 6, 8, 5] 1 5 6 8 5 1 6 8 5
Removing items from a list

• You can remove item using the index by using the pop() method.
• If there is no index specified it will remove the last item.
5
lst = [1, 5, 6, 8, 5] 0 1 2 3 4 0 1 2 3
item = [Link]()
print(item) -> 5 1 5 6 8 5 1 5 6 8
print(lst) -> [1, 5, 6, 8]

lst = [1, 5, 6, 8, 5]
item = [Link](2)
0 1 2 3 4 0 1 2 3
print(item) -> 6
print(lst) -> [1, 5, 8, 5] 1 5 6 8 5 1 5 8 5
Removing items from a list

• You can also use the del keyword that can delete an item at given index
lst = [1, 5, 6, 8, 5]
0 1 2 3 4 0 1 2 3
del lst[2]
print(lst) -> [1, 5, 8, 5] 1 5 6 8 5 1 5 8 5

Example 4: Let the user delete items from grocery list when he get that item (by using the item name or index).
Modifying a list

•The list is mutable not like the String that is immutable


s = 'hallo python’
s[1] = ‘e’ -> (TypeError: 'str' object does not support item assignment)

•The assignment operator can be used to modify or replace a single item of the list
lst = [20, 'ahmed', 15, 70] 0 1 2 3
lst[2] = 30 20 ahmed 15 70
print(lst) -> [20, 'ahmed', 30, 70]

0 1 2 3

20 ahmed 30 70
Modifying a list

•Example 5: Create a program that allow the user to enter his grades and modify the inserted grades and
print the average of his grades.
Slicing: Access Elements

• you can access a range of elements from the list using the slicing

lst = [10, 20, 30, 40, 50, 60, 70]

print(lst[1:5]) -> [20, 30, 40, 50]


print(lst[1:2]) -> [20]
print(lst[5:3]) -> []
print(lst[4:-1]) -> [50, 60]
print(lst[1:]) -> [20, 30, 40, 50, 60, 70]
print(lst[:3]) -> [10, 20, 30]
print(lst[:])->[10, 20, 30, 40, 50, 60, 70]
Slicing: Access Elements

• you can access a range of elements from the list using the slicing
lst = [10, 20, 30, 40, 50, 60, 70]
#lst[start : stop : step]
print(lst[1:6:1]) -> [20, 30, 40, 50, 60] step 1,2,3,……

print(lst[1:6:2]) -> [20, 40, 60] 0 1 2 3 4 5 6


print(lst[1:2:4]) -> [20] 10 20 30 40 50 60 70
print(lst[5:3:-1]) -> [60, 50] -6 -5 -4 -3 -2 -1
-7
print(lst[5::-1]) -> [60, 50, 40, 30, 20, 10]
step -1,-2,-3,……
print(lst[5:-1:-1]) -> []
print(lst[::2]) -> [10, 30, 50, 70]
print(lst[::-1]) -> [70, 60, 50, 40, 30, 20, 10]
Slicing : Removing items

• Slice notation can be used to delete multiple items in a list

lst = [1, 2, 3, 4, 5, 6, 7, 8] 0 1 2 3 4 5 6 7

del lst[:2] 1 2 3 4 5 6 7 8
print(lst) -> [3, 4, 5, 6, 7, 8]

lst = [1, 2, 3, 4, 5, 6, 7, 8] 0 1 2 3 4 5 6 7
del lst[:5:2] 1 2 3 4 5 6 7 8
print(lst) -> [2, 4, 6, 7, 8]
Slicing: Modifying a list

•Slicing can be used to replace multiple items.


lst = [20, 'BMW', 89 , 'Skoda', 60] 0 1 2 3 4

lst[:2] = [90,'Kia'] 20 BMW 89 Skoda 60


print(lst) -> [90, 'Kia', 89, 'Skoda', 60]

lst = [17, 90, 15, 96, 40, 32] 0 1 2 3 4 5


lst[1:5:2] = [77, 12] 17 90 15 96 40 32
print(lst) -> [17, 77, 15, 12, 40, 32]

0 1 2 3 4 5
lst = [17, 90, 15, 96, 40, 32]
17 90 15 96 40 32
lst[::2] = ['BMW', 'Mercedes', 'Skoda']
print(lst) -> ['BMW', 90, 'Mercedes', 96, 'Skoda', 32]
List operations – Membership

•in and not in can be used to detect the membership of an item in a list.
lst = ['BMW', 'Kia', 'Mercedes', 'Skoda']
print('BMW' in lst) -> True
print('Fiat' in lst) -> False
print('Fiat' not in lst) -> True
• Write a program that add new student but there is no duplicated names allowed
List operations – Concatenation

•The + operator can be used to join two lists


lst1 = [1,2,3]
lst2 = [4,5,6]
lst3 = lst1+lst2
print(lst3) -> [1, 2, 3, 4, 5, 6]

• The += operator joins two lists and assigns it to the target list
lst = [1,2,3]
lst += [4,5,6]
print(lst) -> [1, 2, 3, 4, 5, 6]
List operations – Concatenation & Repetition

• It can be used to add one item to the list.


lst = [80, 70, 96]
newGrade = int(input('enter a new grade: ’)) <- 88
lst += [newGrade]
print(lst) -> [80, 70, 96, 88]

Repetition

•The * operator repeats the items of the list, number of items as specified by the integer operand.
lst = [1, 2, 3]
print(lst*3) -> [1, 2, 3, 1, 2, 3, 1, 2, 3]
Built-in Functions can be used with lists

• Get the maximum item using the max()


lst = [4, 8, 2, 1, 3]
print(max(lst)) -> 8

• Get the minimum item using the min()


lst = [4, 8, 2, 1, 3]
print(min(lst)) -> 1

• Get the summation using the sum()


lst = [4, 8, 2, 1, 3]
print(sum(lst)) -> 18
Lists methods

• Counting or locating items.


• an index can be located using index(x, i, j), this method will return the first occurrence of the item at or
after index i and before index j
• In case i and j are not specified they default to i =0 and j = len(lst)
lst = [34, 4, 6, 23, 4]
0 1 2 3 4
#[Link](item, at or after, before)
34 4 6 23 4
print([Link](4)) -> 1
print([Link](4, 3)) -> 4
print([Link](6, 1, 4)) -> 2
Lists methods

• count() method used to count the occurrence(s) of an item in a list.


lst = [34, 4, 6, 23, 4]
print([Link](4)) -> 2
print([Link](6)) -> 1

• reverse() method can be used to reverse a list in-place.


lst = ['A', 'B', 2, 4, 'C']
[Link]()
print(lst) -> ['C', 4, 2, 'B', 'A']
Lists methods

• sort() method can be used to sorts the items.


lst = [34, 4, 6, 23]
[Link]()
print(lst) -> [4, 6, 23, 34]

o reverse arguments – is a boolean that specifies the sorting descending order.


lst = ['Oh', 'Hi', 'Py', 'ed']
[Link]()
print(lst) -> ['Hi', 'Oh', 'Py', 'ed']

lst = ['Oh', 'Hi', 'Py', 'ed']


[Link](reverse=True)
print(lst) -> ['ed', 'Py', 'Oh', 'Hi’]
Copy and Reference

lst = [2, 4, 6, 8]
The expression lst is a reference to the list, while lst[2] is a
reference to a particular element in the list.
a = [10, 20, 30, 40]
b = [10, 20, 30, 40]
print('a =', a) -> a = [10, 20, 30, 40]
print('b =', b) -> b = [10, 20, 30, 40]
b[2] = 35
print('a =', a) -> a = [10, 20, 30, 40]
print('b =', b) -> b = [10, 20, 35, 40]
Reassigning an element of list b does not affect list a
Copy and Reference

a = [10, 20, 30, 40]


b = a
print('a =', a) -> a = [10, 20, 30, 40]
print('b =', b) -> b = [10, 20, 30, 40]
b[2] = 35
print('a =', a) -> a = [10, 20, 35, 40]
print('b =', b) -> b = [10, 20, 35, 40]

the second assignment statement causes variables a


and b to refer to the same list object. We say that a and
b are aliases. Reassigning b[2] changes a[2] as well.
Copy and Reference

• The familiar == equality operator determines if two lists contain the same elements.
• The is operator determines if two variables alias the same list.
# a and b are distinct lists that contain the same elements
a = [10, 20, 30, 40]
b = [10, 20, 30, 40]
print('Is ', a, ' equal to ', b, '?', sep='', end=' ‘)
print(a == b)
print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ')
print(a is b)
output:
Copy and Reference

• The familiar == equality operator determines if two lists contain the same elements.
• The is operator determines if two variables alias the same list.
# c and d alias are distinct lists that contain the same elements
c = [100, 200, 300, 400]
d = c # Makes d an alias of c
print('Is ', c, ' equal to ', d, '?', sep='', end=' ')
print(c == d)
print('Are ', c, ' and ', d, ' aliases?', sep='', end=' ')
print(c is d)
output:
Copy and Reference

• a copy is required so one can change one copy without changing the other.
• the problem:
old_l = [1, 2, 3]
new_l = old_l
# Checking if both lists are pointing to the same object
print(id(new_l)==id(old_l)) -> True
new_l.append(4)
print(new_l) -> [1, 2, 3, 4]
print(old_l) -> [1, 2, 3, 4]
Copy and Reference

• The copy() method can be used to create a new list containing the items of the original list.
• the solution:
old_l = [1, 2, 3]
# Copying old list into a new list
new_l = old_l.copy()
# Checking if both lists are pointing to the same object
print(id(new_l)==id(old_l)) -> False
new_l.append(4)
print(new_l) -> [1, 2, 3, 4]
print(old_l) -> [1, 2, 3]
Copy and Reference

• Assigning a slice of the entire list ( [:] ) is also equivalent to creating a new copy.
old_l = [1, 2, 3]
new_l = old_l[:]
# Checking if both lists are pointing to the same object
print(id(new_l)==id(old_l)) -> False
new_l.append(4)
print(new_l) -> [1, 2, 3, 4]
print(old_l) -> [1, 2, 3]
Summery of list methods
Python programming
Data Structure – Lists
● Lists
● Tuples
● Sets
● Dictionaries
Multidimensional Lists (Nested List)

• A list represents a one-dimensional (1D), linear data structure.


[9, 17, 88, 2, 17, 6, 45]
• Some kinds of information are better represented two-dimensionally, in a rectangular array of elements,
also known as a matrix
• In Python we can express a 2D matrix as a list of lists 0 1 2 3 4
matrix = [[100, 14, 8, 22, 71], 0 100 14 8 22 71

[ 0, 243, 68, 1, 30], 1 0 243 68 1 30

[ 90, 21, 7, 67, 112], 2 90 21 7 67 112

[115, 200, 70, 150, 8]]


3 115 200 70 150 8

print(matrix) -> [[100, 14, 8, 22, 71], [0, 243, 68, 1, 30], [90, 21, 7, 67,
112], [115, 200, 70, 150, 8]]
Multidimensional Lists (Nested List)

• We must use two indices to access an element in our 2D list.


matrix = [[100, 14, 8, 22, 71], [0, 243, 68, 1, 30], [90, 21, 7, 67, 112], [115, 200, 70, 150, 8]]

0 1 2 3 4
print(matrix[2]) -> [90, 21, 7, 67, 112]
0 100 14 8 22 71
print(matrix[2][3]) -> 67
1 0 243 68 1 30
2 90 21 7 67 112
3 115 200 70 150 8

0 1 2 3

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

100 14 8 22 71 0 243 68 1 30 90 21 7 67 112 115 200 70 150 8


Access elements

every element in the multidimensional list can have a different length. 0 1 2 3 4 5 6


ragged = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67

print(ragged[0][2]) -> 8 3 115 200 70 150 8 45 60


print(ragged[1][2]) -> IndexError: list index out of range
print(ragged[-1][-1]) -> 60
print(ragged[-3][-3]) -> IndexError: list index out of range
print(ragged[-3][-1]) -> 243
print(ragged[:][-1]) -> [115, 200, 70, 150, 8, 45, 60]

0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Access elements

• We must use two indices to access an element in our 2D list.


0 1 2 3 4
0 100 14 8 22 71
1 0 243 68 1 30
print(matrix[2][:]) -> [90, 21, 7, 67, 112]
2 90 21 7 67 112
print(matrix[:][1]) -> [0, 243, 68, 1, 30]
3 115 200 70 150 8
print(matrix[:][:]) -> [[100, 14, 8, 22, 71], [0, 243, 68, 1, 30], [90, 21, 7,
67, 112], [115, 200, 70, 150, 8]]
print(matrix[::-1]) -> [[115, 200, 70, 150, 8], [90, 21, 7, 67, 112], [0, 243,
68, 1, 30], [100, 14, 8, 22, 71]]
0 1 2 3

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

100 14 8 22 71 0 243 68 1 30 90 21 7 67 112 115 200 70 150 8


Modify elements

You can also set values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67

lst[0] = [22, 5, 6, 9] 3 115 200 70 150 8 45 60


lst[2][0] = 100
lst[-1] = 15
lst[1][:] = [17, 18]
print(lst) -> [[22, 5, 6, 9], [17, 18], [100, 21, 7, 67], 15]

0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Add elements

You can also add values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67

[Link](9) 3 115 200 70 150 8 45 60


print(lst) -> [[100, 14, 8, 22, 71], [0, 243], [90, 21, 7, 67], [115, 200, 70,
150, 8, 45, 60], 9]
[Link]([93, 65, 83])
print(lst) -> [[100, 14, 8, 22, 71], [0, 243], [90, 21, 7, 67], [115, 200, 70,
150, 8, 45, 60], 9, [93, 65, 83]]

0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Add elements

You can also add values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67

lst[1].append(98) 3 115 200 70 150 8 45 60


print(lst) -> [[100, 14, 8, 22, 71], [0, 243, 98], [90, 21, 7, 67], [115, 200,
70, 150, 8, 45, 60]]
lst[1] += [74, 65]
print(lst) -> [[100, 14, 8, 22, 71], [0, 243, 98, 74, 65], [90, 21, 7, 67], [115,
200, 70, 150, 8, 45, 60]]

0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Add elements

You can also add values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67
3 115 200 70 150 8 45 60
[Link](0, 88)
print(lst,'\n’) -> [88, [100, 14, 8, 22, 71], [0, 243], [90, 21, 7, 67], [115,
200, 70, 150, 8, 45, 60]]
[Link](1, [99, 544, 735])
print(lst,'\n’) -> [88, [99, 544, 735], [100, 14, 8, 22, 71], [0, 243], [90, 21,
7, 67], [115, 200, 70, 150, 8, 45, 60]]
0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Add elements

You can also add values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67
3 115 200 70 150 8 45 60
lst[1].insert(3,90)
print(lst,'\n’) -> [[100, 14, 8, 22, 71], [0, 243, 90], [90, 21, 7, 67], [115,
200, 70, 150, 8, 45, 60]]
lst[-1].extend([11, 66])
print(lst, '\n’) -> [[100, 14, 8, 22, 71], [0, 243, 90], [90, 21, 7, 67], [115,
200, 70, 150, 8, 45, 60, 11, 66]]
0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Remove elements
0 1 2 3 4 5 6

You can also delete values inside the 2D lists as the following: 0 100 14 8 22 71
lst = [[100, 14, 8, 22, 71], 1 0 243
[ 0, 243],
[ 90, 21, 7, 67],
2 90 21 7 67
[115, 200, 70, 150, 8, 45, 60]] 3 115 200 70 150 8 45 60
[Link]([0, 243])
print(lst, '\n’) -> [[100, 14, 8, 22, 71], [90, 21, 7, 67], [115, 200, 70, 150,
8, 45, 60]]
[Link](100) -> ValueError: [Link](x): x not in list
lst[0].remove(100)
print(lst, '\n’) -> [[14, 8, 22, 71], [90, 21, 7, 67], [115, 200, 70, 150, 8, 45,
60]]
0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Remove elements

You can also delete values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67
item = [Link]()
3 115 200 70 150 8 45 60
print(item) -> [115, 200, 70, 150, 8, 45, 60]
print(lst, '\n’) -> [[100, 14, 8, 22, 71], [0, 243], [90, 21, 7, 67]]
item = [Link](1)
print(item) -> [0, 243]
print(lst, '\n’) -> [[100, 14, 8, 22, 71], [90, 21, 7, 67]]

0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Remove elements

You can also delete values inside the 2D lists as the following: 0 1 2 3 4 5 6
lst = [[100, 14, 8, 22, 71], 0 100 14 8 22 71
[ 0, 243],
[ 90, 21, 7, 67], 1 0 243
[115, 200, 70, 150, 8, 45, 60]] 2 90 21 7 67
item = lst[2].pop(1)
3 115 200 70 150 8 45 60
print(item) -> 21
print(lst, '\n') -> [[100, 14, 8, 22, 71], [0, 243], [90, 7, 67], [115, 200, 70,
150, 8, 45, 60]]
item = lst[3].pop(-1)
print(item) -> 60
print(lst, '\n') -> [[100, 14, 8, 22, 71], [0, 243], [90, 7, 67], [115, 200, 70,
150, 8, 45]]
0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Remove elements
0 1 2 3 4 5 6
You can also delete values inside the 2D lists as the following: 0 100 14 8 22 71
lst = [[100, 14, 8, 22, 71], 1 0 243
[ 0, 243],
[ 90, 21, 7, 67], 2 90 21 7 67
[115, 200, 70, 150, 8, 45, 60]] 3 115 200 70 150 8 45 60
del lst[2]
print(lst, '\n’) -> [[100, 14, 8, 22, 71], [0, 243], [115, 200, 70, 150, 8, 45,
60]]
del lst[0][-1]
print(lst, '\n') -> [[100, 14, 8, 22], [0, 243], [115, 200, 70, 150, 8, 45, 60]]
del lst[-1][1:3]
print(lst, '\n') -> [[100, 14, 8, 22], [0, 243], [115, 150, 8, 45, 60]]
0 1 2 3
0 1 2 3 4 0 1 0 1 2 3 0 1 2 3 4 5 6

100 14 8 22 71 0 243 90 21 7 67 115 200 70 150 8 45 60


Traversing a 2D List

you can traverse over a 2D list using nested for


0 1 2 3 4
matrix = [[100, 14, 8, 22, 71],
[ 0, 243, 68, 1, 30], 0 100 14 8 22 71
[ 90, 21, 7, 67, 112], 1 0 243 68 1 30
[115, 200, 70, 150, 8]]
2 90 21 7 67 112
for row in matrix: 3 115 200 70 150 8
for element in row:
print(element,' ', end= '')
print()
0 1 2 3

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

100 14 8 22 71 0 243 68 1 30 90 21 7 67 112 115 200 70 150 8


Traversing a 2D List

you can traverse over a 2D list using nested for

matrix = [[100, 14, 8, 22, 71], 0 1 2 3 4


[ 0, 243, 68, 1, 30],
0 100 14 8 22 71
[ 90, 21, 7, 67, 112],
[115, 200, 70, 150, 8]] 1 0 243 68 1 30
2 90 21 7 67 112
for i in range(len(matrix)):
for j in range(len(matrix[i])): 3 115 200 70 150 8
print(matrix[i][j],' ',end = '')
print()
0 1 2 3

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

100 14 8 22 71 0 243 68 1 30 90 21 7 67 112 115 200 70 150 8


Multidimension list – usage

we can use the Nested List as following:


0 1 2 3
lst = [["Kia", "Sonnet", 2019, 4],
["Toyota", "Camry", 2018, 4], 0 Kia Sonnet 2019 4
["BMW", "Z4", 2015, 4], 1 Toyota Camry 2018 4
["BMW", "S1000", 2016, 2],
2 BMW Z4 2015 4
["KTM", "390", 2019, 2]]
3 BMW S1000 2016 2
• get all the cars brands 4 KTM 390 2019 2
• get the newest car and the oldest one
• get the car data by searching the car name
3-dimensional lists (list in list in list)

lst = [[[111, 112, 113], [121, 122, 123], [131, 132, 133]],
[[211, 212, 213], [221, 222, 223], [231, 232, 233]],
[[311, 312, 313], [321, 322, 323], [331, 332, 333]]]
3-dimensional lists (list in list in list)

lst = [[[111, 112, 113], [121, 122, 123], [131, 132, 133]],
[[211, 212, 213], [221, 222, 223], [231, 232, 233]],
[[311, 312, 313], [321, 322, 323], [331, 332, 333]]]
3-dimensional lists (list in list in list)

lst = [[[111, 112, 113], [121, 122, 123], [131, 132, 133]],
[[211, 212, 213], [221, 222, 223], [231, 232, 233]],
[[311, 312, 313], [321, 322, 323], [331, 332, 333]]]

print(lst[1]) -> [[211, 212, 213], [221, 222, 223], [231, 232,
233]]
print(lst[2][1]) -> [321, 322, 323]
print(lst[1][0][2]) -> 213 0 1 2

0 1 2 0 113 123 133

0 112 122 132 1 213 223 233


0 1 2 1 212 222 232 2 313 323 333
0 111 121 131 2 312 322 332
1 211 221 231
2 311 321 331
Python programming
Data Structure – Tuples
● Lists
● Tuples
● Sets
● Dictionaries
What are Tuples?

● Tuple items are ordered, unchangeable, and allow duplicate values.


● The tuple is the same as List, but the only difference is the Tuples are immutable that means once you
create the tuple object, you are not allowed to make any changes to the tuple object.
● Tuples are written with round brackets ( ) .

a = (30, 10, 20)


b = ("Suresh", "Rohini", "Trishi", "Hanshith")
c = (10, "Tutlane", 20)
print("a = ", a) -> (30, 10, 20)
print("b = ", b) -> ('Suresh', 'Rohini', 'Trishi', 'Hanshith')
print("c = ", c) -> (10, 'Tutlane', 20)
Access Elements from Tuple

● you can access elements from the tuple object by using index values.

tpl = (10, 20, 30, "python")


print(tpl[0]) -> 10
print(tpl[3]) -> python

• In python, you can also use negative indexing to access tuple object elements starting from the end. The index
value -1 will refer to the last item, -2 refers to the second-last item, and so on.

print(tpl[-1]) -> python


print(tpl[-3]) -> 20
Access Range of Values from Tuple

• you can use index ranging by specifying the starting and ending positions with the colon ( : ) operator.
tpl = (10, 20, 30, "learn", "python")

print(tpl[1:4]) -> (20, 30, 'learn’)


print(tpl[:]) -> (10, 20, 30, 'learn', 'python')
print(tpl[2:]) -> (30, 'learn', 'python')
print(tpl[:4]) -> (10, 20, 30, 'learn’)
print(tpl[:-1]) -> (10, 20, 30, 'learn’)
print(tpl[-3:-1]) -> (30, 'learn')
print(tpl[-4:-2]) -> (20, 30)
Create Tuple with One Item

If you want to create a tuple object with one item, add a comma (,) after the item; otherwise, python will not
consider it as a tuple object.

tpl = ("tutlane",)
print(type(tpl)) -> <class 'tuple'>

# Not a tuple
tpl1 = ("tutlane")
print(type(tpl1)) -> <class 'str'>
Change Tuple Item Value

As discussed, tuples are immutable so, if you try to change the tuple object by modifying the existing values,
you will get an exception like as shown below.

a = (30, 10, 20, "python")


a[0] = 50 -> TypeError: 'tuple' object does not support item assignment
print("a = ", a)
Change Tuple Item Value

• To change the tuple item values first, you need to convert the tuple into a list, change/update the list item
values, and convert the list back into a tuple.

tpl = (10, 20, 30, "python", "programming")


print("Before: ",tpl) -> Before: (10, 20, 30, 'python', 'programming')
lst = list(tpl)
lst[1] = 5
lst[3] = 40
lst[4] = 50
tpl = tuple(lst)
print("After: ",tpl) -> After: (10, 5, 30, 40, 50)
Add or Append Items to Tuple

• tuple objects are immutable so, if you try to add new items to a tuple object, you will get
a TypeError exception.

tpl = (10, 20, 30)


print("Before: ",tpl)
tpl[3] = 40 -> TypeError: 'tuple' object does not support item assignment
tpl[4] = 50
print("After: ",tpl)
Add or Append Items to Tuple

• To add items to the tuples first, you need to convert the tuple into a list, add the list items, and convert the
list back into a tuple.

tpl = (10, 20, 30)


print("Before: ",tpl) -> Before: (10, 20, 30)
lst = list(tpl)
[Link](40)
[Link](50)
tpl = tuple(lst)
print("After: ",tpl) -> After: (10, 20, 30, 40, 50)
Remove Elements from Tuple

• The tuple object is immutable, so it won’t allow you to remove the tuple elements, but by using the del
keyword, you can delete the tuple completely.

tpl = (10, 20, 30, "python", "programming")

print("Before: ", tpl) -> Before: (10, 20, 30, 'python', 'programming')
del tpl
print("After: ", tpl) -> NameError: name 'tpl' is not defined
Remove Elements from Tuple

• To remove items from the tuples first, you need to convert the tuple into a list, remove the list items, and
convert the list back into a tuple.

tpl = (10, 20, 30, "python", "programming")

print("Before: ", tpl) -> Before: (10, 20, 30, 'python', 'programming’)
lst = list(tpl)
[Link]("python")
del lst[-1]
tpl = tuple(lst)
print("After: ", tpl) -> After: (10, 20, 30)
Join or Concatenate Tuples

• The + operator is useful to join or concatenate multiple tuples and return a new tuple with all the tuples
elements.

tpl1 = (10, 20, "python")


tpl2 = (10, "programming", "course")
tpl3 = tpl1 + tpl2
print(tpl3) -> (10, 20, 'python', 10, 'programming', 'course’)
Tuple Traversal & Tuple Methods

• By using for loop, you can loop through the items of tuple object based on your requirements.
tpl = (10, 20, 30, "python", "programming", 10)
for item in tpl:
print(item)

print([Link]('python’)) -> 3
print([Link](10)) -> 2
Python programming
Data Structure – Sets
● Lists
● Tuples
● Sets
● Dictionaries
What is Set?

• Sets are written with curly brackets.


• Set items are unordered, unchangeable, and do not allow duplicate values.

a = {30, 10, 10, 20}


b = {"python", "programming", "course"}
c = {30, 10, 10, 20, "python", "programming"}
print("a = ", a) -> a = {10, 20, 30}
print("b = ", b) -> b = {'course', 'programming', 'python'}
print("c = ", c) -> c = {'programming', 10, 20, 30, 'python’}

• If you observe the above result, the Set collection has returned the unique elements of the unordered list.
Access Elements from Set

• a set must contain at least one element, if you want to create a set with no elements use the set()
expression
s = {}
st = set()
print(type(s)) -> <class 'dict'>
print(type(st)) -> <class 'set'>
• it’s impossible to access the set elements using index values because it will store the items in an
unordered manner, you can loop through the items of a set to access them.
st = {10, 20, 30, "python", "programming"}
for item in st:
print(item)
Add or Append Items to Set

• Once you create the python set, it won’t allow you to change the set item values. Instead, it will allow you to
add or append new items to the set using add() or update() methods.
• The add() method is useful when you want to add only one item at a time to the set()

st = {10, 20, "learn", "python"}


[Link](30)
[Link]("programming")
print(st) -> {'learn', 'programming', 10, 20, 30, 'python'}
Add or Append Items to Set

• If you want to add multiple items at a time to set, use update() method.

st = {10, 20, "learn", "python"}


[Link]([30, "programming"])
print(st) -> {'learn', 'programming', 10, 20, 30, 'python’}

• Get Length of Set

st = {10, 10, 20, 20, 30, "python", "programming"}


print("Set Size: ", len(st)) -> Set Size: 5
Remove Elements from Set

• you can delete/remove items from a set using either del keyword, remove(), discard(), pop(), or clear()
methods based on our requirements.
• if you want to remove set items based on the value, you can use the set remove() method.

st = {10, 20, 30, "python", "programming"}


print("Before: ", st) -> Before: {10, 20, 'python', 30, 'programming'}
[Link](20)
[Link]("python")
print("After: ", st) -> After: {10, 30, 'programming’}

• The remove() method will throw an exception when the defined value is not found in the set.
Remove Elements from Set

• The discard() method is same as the remove() method but, the only difference is the discard() method will
not throw an exception, and even the defined value is not found in the set.

st = {10, 20, 30, "python", "programming"}


print("Before: ", st) -> Before: {10, 20, 'python', 30, 'programming'}
[Link](20)
[Link]("python")
[Link](50)
print("After: ", st) -> After: {10, 30, 'programming'}
Remove Elements from Set

• the set pop() method is also useful to remove the set items, but this method will remove the last item. As
discussed, the sets are unordered, and you will not know which item gets deleted.
st = {10, 20, 30, "python", "programming"}
print("Before: ", st) -> Before: {10, 20, 'python', 30, 'programming'}
[Link]()
print("After: ", st) -> After: {20, 'python', 30, 'programming'}
• If you want to clear or empty set items, you can use the set clear() method.
st = {10, 20, 30, "python", "programming"}
print("Before: ", st) -> Before: {10, 20, 'python', 30, 'programming'}
[Link]()
print("After: ", st) -> After: set()
Remove Elements from Set

• If you want to delete the set completely, you can use the del keyword.

st = {10, 20, 30, "python", "programming"}


print("Before: ", st)
del st
print("After: ", st) -> NameError: name 'st' is not defined
Join or Concatenate Sets

• the set methods such as union() and update() methods are useful to join or concatenate multiple sets.
• The union() method will return a new set containing all the items from the mentioned sets and exclude the
duplicates.
st1 = {10, 20, "learn"}
st2 = {10, "python", "programming"}
st3 = [Link](st2)
print(st3) -> {'learn', 20, 'python', 10, 'programming’}
• The update() method will join the sets by inserting all the items of one set into another set.
[Link](st2)
print(st1) -> {'learn', 20, 'python', 10, 'programming'}
Python Set Methods
Python programming
Data Structure – Dictionaries
● Lists
● Tuples
● Sets
● Dictionaries
What is the Dictionary ?

• Dictionaries are used to store data values in key:value pairs.


• Dictionaries are written with curly brackets { }, and have keys and values:
• Dictionary items are ordered, changeable, and allow duplicates.

a = {1: 30, 2: 20}


b = {"Name": "Hashem Alsaqqa", "location": "Gaza"}
c = {1: "Welcome", "Id": 10}
print("a = ", a) -> a = {1: 30, 2: 20}
print("b = ", b) -> b = {'Name': 'Hashem Alsaqqa', 'location': 'Gaza'}
print("c = ", c) -> c = {1: 'Welcome', 'Id': 10}
Access Dictionary Items

• You can access dictionary elements, either using the key name inside square brackets [ ] or using the
key name inside the get() method.

• by using the key name :


dct = {"Id": 1, "Name": "Hashem", "Location": "Gaza"}
uid = dct["Id"]
name = dct["Name"]
location = dct["Location"]
print("Id = {}, Name = {}, Location = {}".format(uid, name, location)) -> Id =
1, Name = Hashem, Location = Gaza
Access Dictionary Items

• by using the get() method:


dct = {"Id": 1, "Name": "Hashem", "Location": "Gaza"}
uid = [Link]("Id")
name = [Link]("Name")
location = [Link]("Location")
print("Id = {}, Name = {}, Location = {}".format(uid, name, location)) -> Id =
1, Name = Hashem, Location = Gaza

• if you used key name that does not exist with the get() method, it will return None.
print('age = ',[Link]('age’)) -> age = None
Change Dictionary Item Values

• Using key values, you can change or update the value of the required item in the dictionary.

dct = {"Id": 1, "Name": "Hashem", "Location": "Gaza"}


print("Before: ",dct) -> Before: {'Id': 1, 'Name': 'Hashem', 'Location': 'Gaza'}
dct["Id"] = 10
dct["Name"] = "Ahmed"
dct["Location"] = "Ramallah"
print("After: ",dct) -> After: {'Id': 10, 'Name': 'Ahmed', 'Location': 'Ramallah'}
Add Items to Dictionary

• you can add items to the dictionary by assigning a value to the new keys.

mbl = {"Brand": "Oneplus", "Model": "8T"}


print("Before: ",mbl) -> Before: {'Brand': 'Oneplus', 'Model': '8T'}
mbl["Color"] = "Aqua"
mbl["Type"] = "5G"
print("After: ",mbl) -> After: {'Brand': 'Oneplus', 'Model': '8T', 'Color':
'Aqua', 'Type': '5G'}
Remove Items from Dictionary

• you can delete/remove items from dictionary object using either del keyword, pop(), popitem(), or clear()
methods based on our requirements.
• The del keyword is useful for removing dictionary items with the specified key name or deleting the dictionary
completely.
mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua", "Type": "5G"}
print("Before: ",mbl) -> Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color':
'Aqua', 'Type': '5G'}
del mbl["Color"]
del mbl["Type"]
print("After: ",mbl) -> After: {'Brand': 'Oneplus', 'Model': '8T'}
Remove Items from Dictionary

• the dictionary pop() method is useful to remove the dictionary items based on the specified key name.
mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua", "Type": "5G"}
print("Before: ",mbl) -> Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color':
'Aqua', 'Type': '5G'}
[Link]("Color")
[Link]("Type")
print("After: ",mbl) -> After: {'Brand': 'Oneplus', 'Model': '8T’}
• Instead of using dictionary keys, you can use popitem() method in python to delete the last inserted item.
[Link]()
print("After: ",mbl) -> After: {'Brand': 'Oneplus', 'Model': '8T', 'Color':
'Aqua'}
Remove Items from Dictionary

• If you want to clear or empty dictionary items, you can use the dictionary clear() method.
mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
print("Before: ",mbl) -> Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color':
'Aqua'}
[Link]()
print("After: ",mbl) -> After: {}

• To count the number of items (key-value pairs) in the list, use the len() function.
mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
print("Dictionary Size: ", len(mbl)) -> Dictionary Size: 3
Join or Concatenate Dictionaries

• You can use an update() method to join or merge multiple dictionaries with all the list elements in python.
dct1 = {1: 10, 2: 20}
dct2 = {"name": "ahmed", "location": "Gaza"}
[Link](dct2)
print(dct1) -> {1: 10, 2: 20, 'name': 'ahmed', 'location': 'Gaza’}
• If two dictionaries (dct1, dct2) have the same keys, the update() method will consider using the values of the
second dictionary (dct2).
dct1 = {1: 10, 2: 20, "location": "Nablus"}
dct2 = {1: 30, "name": "Ahmed", "location": "Gaza"}
[Link](dct2)
print(dct1) -> {1: 30, 2: 20, 'location': 'Gaza', 'name': 'Ahmed'}
Check If Dictionary has Key or Value

• By using in and not in operators, you can check whether the specified key exists in the dictionary or not.
dct = {1: 10, "name": "Omar", "location": "Gaza"}
print("1 in dict: ", 1 in dct) -> 1 in dict: True
print("name in dict: ", "name" in dct) -> name in dict: True
print("50 in dict: ", 50 in dct) -> 50 in dict: False

• By using in and not in operators with values() method, you can check if the value exists.
dct = {1: 10, "name": "omar", "location": "Gaza"}
print("omar name in dict: ", "omar" in [Link]()) -> omar name in dict: True
print("Omar name in dict: ", "Omar" in [Link]()) -> Omar name in dict: False
Iterate through Dictionary

• By using for loop, you can iterate through the items of the dictionary, While iterating over dictionary items, it
will return only the keys of the dictionary.
dct = {1: 10, "name": "Anas", "location": "Gaza"}
for item in dct:
print(item, '->' , dct[item], end = ' ')->1 -> 10 name -> Anas location -> Gaza
• you can iterate through the values of the dictionary using the values() method.
dct = {1: 10, "name": "Anas", "location": "Gaza"}
for item in [Link]():
print(item, end='\t’) -> 10 Anas Gaza
Python Nested Dictionary

• you can create a nested dictionary by adding one dictionary inside of another dictionary.
cars = {"car1": {
"brand": "hyundai",
"name": "i10"
},
"car2": {
"brand": "kia",
"name": "sonet"
}}
print(cars) -> {'car1': {'brand': 'hyundai', 'name': 'i10'}, 'car2': {'brand':
'kia', 'name': 'sonet'}}
Python Sort Dictionary Elements

• the sorted() method will sort the dictionary elements based on the keys and values. By default, the sorted()
method will sort the list elements in ascending order.
dct = {4: 10, 1: 20, 5: 30, 3: 60}
print(sorted([Link]())) -> [1, 3, 4, 5]
print(sorted([Link]())) -> [(1, 20), (3, 60), (4, 10), (5, 30)]
print(sorted([Link]())) -> [10, 20, 30, 60]

• To sort the dictionary elements in descending order, you need to use the optional reverse = True property
print(sorted([Link](), reverse = True)) -> [5, 4, 3, 1]
print(sorted([Link](), reverse = True)) -> [(5, 30), (4, 10), (3, 60), (1, 20)]
print(sorted([Link](), reverse = True)) -> [60, 30, 20, 10]
Python Sort Dictionary Elements

• To sort dictionary items either in ascending or descending order, you need to make sure that all the dictionary
keys/values must be the same type; otherwise, you will get a TypeError exception.

dct = {4: 10, 1: 20, "name": "suresh", "location": "guntur"}


print(sorted([Link](), reverse = True)) -> TypeError: '<' not supported between
instances of 'int' and 'str'
print(sorted([Link](), reverse = True)) -> TypeError: '<' not supported between
instances of 'int' and 'str'
Python Dictionary Methods
Example of using dictionary

• Ascii Table
Example of using dictionary

• Ascii Table
asciiTable = {'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71,
'H': 72, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78,
'O': 79, 'P': 80, 'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85,
'V': 86, 'W': 87, 'X': 88, 'Y': 89, 'Z': 90,
'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101, 'f': 102, 'g': 103,
'h': 104, 'i': 105, 'j': 106, 'k': 107, 'l': 108, 'm': 109, 'n': 110,
'o': 111, 'p': 112, 'q': 113, 'r': 114, 's': 115, 't': 116, 'u': 117,
'v': 118, 'w': 119, 'x': 120, 'y': 121, 'z': 122}

userinput = input('Enter the char to search: ')


if userinput in asciiTable:
print(asciiTable[userinput])
else:
print('enter a valid character pls')
Dictionary Exercises

1. Write a program that repeatedly asks the user to enter product names and prices. Store all of these in a
dictionary whose keys are the product names and whose values are the prices. When the user is done
entering products and prices, allow them to repeatedly enter a product name and print the corresponding
price or a message if the product is not in the dictionary.

2. Using the dictionary created in the previous problem, allow the user to enter a dollar amount and print out all
the products whose price is less than that amount.
Dictionary Exercises

3. For this problem, use the dictionary from the beginning of this chapter whose keys are month
names and whose values are the number of days in the corresponding months.
a) Ask the user to enter a month name and use the dictionary to tell them how many days are
in the month.
b) Print out all of the keys in alphabetical order.
c) Print out all of the months with 31 days.
d) Print out the (key-value) pairs sorted by the number of days in each month
e) Modify the program from part (a) and the dictionary so that the user does not have to
know how to spell the month name exactly. That is, all they have to do is spell the first
three letters of the month name correctly.
Dictionary Exercises

4. Write a program that uses a dictionary that contains ten user names and passwords. The program should ask
the user to enter their username and password. If the username is not in the dictionary, the program should
indicate that the person is not a valid user of the system. If the username is in the dictionary, but the user
does not enter the right password, the program should say that the password is invalid. If the password is
correct, then the program should tell the user that they are now logged in to the system.

5. Write a program that converts Roman numerals into ordinary numbers. Here are the conversions: M=1000,
D=500, C=100, L=50, X=10, V=5 I=1. Don't forget about things like IV being 4 and XL being 40.

6. Write a program that converts ordinary numbers into Roman numerals


Dictionary Exercises

7. Repeatedly ask the user to enter a team name and the how many games the team won and how many they
lost. Store this information in a dictionary where the keys are the team names and the values are lists of the
form [wins, losses].
a) Using the dictionary created above, allow the user to enter a team name and print out the team's winning
percentage.
b) Using the dictionary, create a list whose entries are the number of wins of each team.
c) Using the dictionary, create a list of all those teams that have winning records.

You might also like