0% found this document useful (0 votes)
4 views111 pages

Python

Python is a versatile programming language created in 1991, used for web development, software development, and data handling. It features a simple syntax that enhances readability and allows for rapid prototyping, and it supports various programming paradigms. The document also covers Python's data structures, particularly tuples, their properties, and how to manipulate them.

Uploaded by

Pema Samdrup
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)
4 views111 pages

Python

Python is a versatile programming language created in 1991, used for web development, software development, and data handling. It features a simple syntax that enhances readability and allows for rapid prototyping, and it supports various programming paradigms. The document also covers Python's data structures, particularly tuples, their properties, and how to manipulate them.

Uploaded by

Pema Samdrup
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

Python Introduction

What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify
files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.

Good to know
• The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.

1
Python Syntax compared to other programming
languages
• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope, such as
the scope of loops, functions, and classes. Other programming
languages often use curly brackets for this purpose.

Python Getting Started


Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start
bar for Python or run the following on the Command Line ([Link]):

C:\Users\Your Name>python –version

To check if you have python installed on a Linux or Mac, then on linux open
the command line or on Mac open the Terminal and type:

python --version

If you find that you do not have Python installed on your computer, then you
can download it for free from the following website: [Link]

Python Quickstart
Python is an interpreted programming language, this means that as a
developer you write Python (.py) files in a text editor and then put those files
into the python interpreter to be executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python [Link]

Where "[Link]" is the name of your python file. Let's write our first
Python file, called [Link], which can be done in any text editor.
[Link]

print("Hello, World!")
Hello, World!

Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:

2
C:\Users\Your Name>python [Link]

The output should read:

Hello, World!

Congratulations, you have written and executed your first Python program.

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest
not to write the code in a file. This is made possible because Python can be
run as a command line itself.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python

Or, if the "python" command did not work, you can try "py":

C:\Users\Your Name>py

From there you can write any python, including our hello world example from
earlier in the tutorial:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")

Which will write "Hello, World!" in the command line:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!

Whenever you are done in the python command line, you can simply type
the following to quit the python command line interface:

exit()

3
Python Tuples
mytuple = ("apple", "banana", "cherry")

Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities and
usage.

A tuple is a collection which is ordered and unchangeable.


Tuples are written with round brackets.

Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

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

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple
items are indexed, the first item has index [0], the second item has
index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.

4
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)

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

Tuple Length
To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the
item, otherwise Python will not recognize it as a tuple.

Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

<class 'tuple'>
<class 'str'>

5
Tuple Items - Data Types
Tuple items can be of any data type:

Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

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


(1, 5, 7, 9, 3)
(True, False, False)

A tuple can contain different data types:

Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")

('abc', 34, True, 40, 'male')

type()
From Python's perspective, tuples are defined as objects with the data type
'tuple':
<class 'tuple'>

Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))

<class 'tuple'>

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the
double round-brackets
print(thistuple)

6
('apple', 'banana', 'cherry')

Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
*Set items are unchangeable, but you can remove and/or add items whenever
you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of


that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.

Access Tuple Items


You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

banana
Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

cherry

7
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new tuple with the
specified items.

Example
Return the third, fourth, and fifth item:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

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

Note: The search will start at index 2 (included) and end at index 5 (not
included). Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example
This example returns the items from the beginning to, but NOT included,
"kiwi":
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])

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

By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])

('cherry', 'orange', 'kiwi', 'melon', 'mango')

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the
tuple:

8
Example
This example returns the items from index -4 (included) to index -1
(excluded)
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

('orange', 'kiwi', 'melon')

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:

Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Yes, 'apple' is in the fruits tuple

Python - Update Tuples


Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created. But there are some workarounds.

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called. But there is a
workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.

Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

("apple", "kiwi", "cherry")

9
Add Items
Since tuples are immutable, they do not have a build-in append() method,
but there are other ways to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you
can convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)

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

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s), and
add it to the existing tuple:

Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)

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

Note: When creating a tuple with only one item, remember to include a
comma after the item, otherwise it will not be identified as a tuple.

Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
use the same workaround as we used for changing and adding tuple items:

Example
Convert the tuple into a list, remove "apple", and convert it back into a
tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)

10
('banana', 'cherry')
Or you can delete the tuple completely:

Example
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
Traceback (most recent call last):
File "demo_tuple_del.py", line 3, in <module>
print(thistuple) #this will raise an error because the tuple
no longer exists
NameError: name 'thistuple' is not defined

Python - Unpack Tuples


Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called
"packing" a tuple:

Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")

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

But, in Python, we are also allowed to extract the values back into variables.
This is called "unpacking":

Example
Unpacking a tuple:

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


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

apple
banana
cherry

11
Note: The number of variables must match the number of values in the
tuple, if not, you must use an asterisk to collect the remaining values as a
list.

Using Asterisk*
If the number of variables is less than the number of values, you can add
an * to the variable name and the values will be assigned to the variable as a
list:

Example
Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")


(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
apple
banana
['cherry', 'strawberry', 'raspberry']

If the asterisk is added to another variable name than the last, Python will
assign values to the variable until the number of values left matches the
number of variables left.

Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
apple
['mango', 'papaya', 'pineapple']
cherry

Python - Loop Tuples


12
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

apple
banana
cherry

Loop Through the Index Numbers


You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

apple
banana
cherry

Using a While Loop


You can loop through the list items by using a while loop. Use
the len() function to determine the length of the tuple, then start at 0 and
loop your way through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.

Example
Print all items, using a while loop to go through all the index numbers:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
apple
banana
cherry

13
Python - Join Tuples
Join Two Tuples
To join two or more tuples you can use the + operator:

Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

('a', 'b', 'c', 1, 2, 3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you
can use the * operator:

Example
Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

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

Python - Tuple Methods


Tuple Methods
Python has two built-in methods that you can use on tuples

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position
of where it was found

14
Python Tuple count() Method
Example
Return the number of times the value 5 appears in the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
2

Definition and Usage


The count() method returns the number of times a specified value appears
in the tuple.

Syntax
[Link](value)

Parameter Values
Parameter Description

value Required. The item to search for

Python Tuple index() Method


Example

Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](8)
print(x)
3

15
Definition and Usage
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.

Syntax
[Link](value)

Parameter Values
Parameter Description

value Required. The item to search for

Python - Tuple Exercises


Test Yourself with Exercises
Now you have learned a lot about tuples, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:

Exercise:
Print the first item in the fruits tuple.

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


print( )

Exercise:
Use the correct syntax to print the number of items in the fruits tuple.

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


print( )

Exercise:
Use negative indexing to print the last item in the tuple.

16
fruits = ("apple", "banana", "cherry")
print( )

Exercise:
Use a range of indexes to print the third, fourth, and fifth item in the tuple.

fruits = ("apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango")
print(fruits[ ])

Python Sets
myset = {"apple", "banana", "cherry"}

Set
Sets are used to store multiple items in a single variable. Set is one of 4 built-
in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage. A set is a
collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new
items.

Sets are written with curly brackets.

Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

{'cherry', 'banana', 'apple'}

Note: Sets are unordered, so you cannot be sure in which order the items
will appear.

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

17
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after
the set has been created.

Once a set is created, you cannot change its items, but you can remove
items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
{'banana', 'cherry', 'apple'}

Get the Length of a Set


To determine how many items a set has, use the len() function.

Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Set Items - Data Types


Set items can be of any data type:

Example
String, int and boolean data types:

18
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)

{'cherry', 'apple', 'banana'}


{1, 3, 5, 7, 9}
{False, True}

A set can contain different data types:

Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
print(set1)
{True, 34, 40, 'male', 'abc'}

type()
From Python's perspective, sets are defined as objects with the data type
'set':
<class 'set'>

Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))

<class 'set'>

The set() Constructor


It is also possible to use the set() constructor to make a set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double
round-brackets
print(thisset)

{'apple', 'banana', 'cherry'}

19
Python Collections (Arrays)
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
*Set items are unchangeable, but you can remove items and add new items.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of


that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.

Python - Access Set Items


Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.

Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

apple
cherry
banana
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

True

20
Change Items
Once a set is created, you cannot change its items, but you can add new
items.

Python - Add Set Items


Add Items
Once a set is created, you cannot change its items, but you can add new
items.

To add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)

{'orange', 'banana', 'cherry', 'apple'}

Add Sets
To add items from another set into the current set, use
the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)

{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}

Add Any Iterable


The object in the update() method does not have to be a set, it can be any
iterable object (tuples, lists, dictionaries etc.).

Example

21
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
[Link](mylist)
print(thisset)

{'banana', 'cherry', 'apple', 'orange', 'kiwi'}

Python - Remove Set Items


Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)

{'cherry', 'apple'}

Note: If the item to remove does not exist, remove() will raise an error.

Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)

{'apple', 'cherry'}

Note: If the item to remove does not exist, discard() will NOT raise an
error.
You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not
know what item that gets removed. The return value of the pop() method is
the removed item.

Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = [Link]()

22
print(x)
print(thisset)

apple
{'cherry', 'banana'}

Note: Sets are unordered, so when using the pop() method, you do not know
which item that gets removed.

Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
set()

Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

Traceback (most recent call last):


File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set no
longer exists
NameError: name 'thisset' is not defined

Python - Loop Sets


Loop Items
You can loop through the set items by using a for loop:

Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

cherry
banana
apple

23
Python - Join Sets
Join Two Sets
There are several ways to join two or more sets in Python. You can use
the union() method that returns a new set containing all items from both sets,
or the update() method that inserts all the items from one set into another:

Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)

{'c', 1, 2, 3, 'a', 'b'}

Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1)

{'b', 'c', 'a', 1, 2, 3}

Note: Both union() and update() will exclude any duplicate items.

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present
in both sets.
Example
Keep the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

{'apple'}

24
The intersection() method will return a new set, that only contains the
items that are present in both sets.

Example
Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)

{'apple'}

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements
that are NOT present in both sets.

Example
Keep the items that are not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

{'google', 'banana', 'microsoft', 'cherry'}

The symmetric_difference() method will return a new set, that contains


only the elements that are NOT present in both sets.
Example
Return a set that contains all items from both sets, except items that are
present in both:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

{'google', 'banana', 'microsoft', 'cherry'}

Python - Set Methods

25
Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference
between two or more sets
difference_update() Removes the items in this set that are
also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of
two other sets
intersection_update() Removes the items in this set that are
not present in other, specified set(s)
isdisjoint() Returns whether two sets have a
intersection or not
issubset() Returns whether another set contains
this set or not
issuperset() Returns whether this set contains
another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric
differences of two sets
symmetric_difference_update() inserts the symmetric differences from
this set and another
union() Return a set containing the union of
sets
update() Update the set with the union of this
set and others

Python Set add() Method


Example
Add an element to the fruits set:

26
fruits = {"apple", "banana", "cherry"}
[Link]("orange")
print(fruits)

{'apple', 'cherry', 'banana', 'orange'}

Definition and Usage


The add() method adds an element to the set.
If the element already exists, the add() method does not add the element.

Syntax
[Link](elmnt)

Parameter Values
Parameter Description

elmnt Required. The element to add to the set

More Examples
Example
Try to add an element that already exists:
fruits = {"apple", "banana", "cherry"}
[Link]("apple")
print(fruits)

{'apple', 'cherry', 'banana'}

Python Set clear() Method


Example
Remove all elements from the fruits set:
fruits = {"apple", "banana", "cherry"}
[Link]()
print(fruits)
set()

Definition and Usage


The clear() method removes all elements in a set.

27
Syntax
[Link]()

Parameter Values
No parameters

Python Set copy() Method


Example
Copy the fruits set:
fruits = {"apple", "banana", "cherry"}
x = [Link]()
print(x)

{'cherry', 'banana', 'apple'}

Definition and Usage


The copy() method copies the set.

Syntax
[Link]()

Parameter Values
No parameters

Python Set difference() Method


Example
Return a set that contains the items that only exist in set x, and not in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)

{'cherry', 'banana'}

Definition and Usage


The difference() method returns a set that contains the difference between
two sets.

28
Meaning: The returned set contains items that exist only in the first set, and
not in both sets.

Syntax
[Link](set)

Parameter Values
Parameter Description

set Required. The set to check for differences in

More Examples
Example
Reverse the first example. Return a set that contains the items that only
exist in set y, and not in set x:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](x)
print(z)

{'microsoft', 'google'}

Python Set difference_update() Method


Example
Remove the items that exist in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
{'cherry', 'banana'}

Definition and Usage


The difference_update() method removes the items that exist in both sets.
The difference_update() method is different from the difference() method,
because the difference() method returns a new set, without the unwanted
items, and the difference_update() method removes the unwanted items
from the original set.

29
Syntax
set.difference_update(set)

Parameter Values
Parameter Description

set Required. The set to check for differences in

Python Set discard() Method


Example
Remove "banana" from the set:
fruits = {"apple", "banana", "cherry"}
[Link]("banana")
print(fruits)

{'apple', 'cherry'}

Definition and Usage


The discard() method removes the specified item from the set.
This method is different from the remove() method, because
the remove() method will raise an error if the specified item does not exist,
and the discard() method will not.

Syntax
[Link](value)

Parameter Values
Parameter Description

value Required. The item to search for, and remove

Python Set intersection() Method

30
Example
Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)

{'apple'}

Definition and Usage


The intersection() method returns a set that contains the similarity between
two or more sets. Meaning: The returned set contains only items that exist in
both sets, or in all sets if the comparison is done with more than two sets.

Syntax
[Link](set1, set2 ... etc)

Parameter Values
Parameter Description

set1 Required. The set to search for equal items in

set2 Optional. The other set to search for equal items in.
You can compare as many sets you like.
Separate the sets with a comma

More Examples
Example
Compare 3 sets, and return a set with items that is present in all 3 sets:
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = [Link](y, z)
print(result)

{'c'}

Python Set intersection_update() Method

31
Example
Remove the items that is not present in both x and y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

{'apple'}

Definition and Usage


The intersection_update() method removes the items that is not present in
both sets (or in all sets if the comparison is done between more than two
sets). The intersection_update() method is different from
the intersection() method, because the intersection() method returns a
new set, without the unwanted items, and
the intersection_update() method removes the unwanted items from the
original set.

Syntax
set.intersection_update(set1, set2 ... etc)

Parameter Values
Parameter Description

set1 Required. The set to search for equal items in

set2 Optional. The other set to search for equal items in.
You can compare as many sets you like.
Separate the sets with a comma

More Examples
Example
Compare 3 sets, and return a set with items that is present in all 3 sets:
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
x.intersection_update(y, z)
print(x)

{'c'}

32
Python Set isdisjoint() Method
Example
Return True if no items in set x is present in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = [Link](y)
print(z)

True

Definition and Usage


The isdisjoint() method returns True if none of the items are present in
both sets, otherwise it returns False.

Syntax
[Link](set)

Parameter Values
Parameter Description

set Required. The set to search for equal items in

More Examples
Example
What if no items are present in both sets? Return False if one ore more items
are present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)

False

Python Set issubset() Method


Example
Return True if all items in set x are present in set y:
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}

33
z = [Link](y)
print(z)

True

Definition and Usage


The issubset() method returns True if all items in the set exists in the
specified set, otherwise it returns False.

Syntax
[Link](set)

Parameter Values
Parameter Description

set Required. The set to search for equal items in

More Examples
Example
What if not all items are present in the specified set? Return False if not all
items in set x is present in set y:

x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b"}
z = [Link](y)
print(z)

False

Python Set issuperset() Method


Example
Return True if all items set y are present in set x:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](y)
print(z)

True

34
Definition and Usage
The issuperset() method returns True if all items in the specified set exists
in the original set, otherwise it retuns False.

Syntax
[Link](set)

Parameter Values
Parameter Description

set Required. The set to search for equal items in

More Examples
Example
What if not all items are present in the specified set?
Return False if not all items in set y are present in set x:
x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = [Link](y)
print(z)

False

Python Set pop() Method


Example
Remove a random item from the set:
fruits = {"apple", "banana", "cherry"}
[Link]()
print(fruits)

{'apple', 'cherry'}

Definition and Usage


The pop() method removes a random item from the set.
This method returns the removed item.

Syntax
[Link]()

35
Parameter Values
No parameter values.

More Examples
Example
Return the removed element:
fruits = {"apple", "banana", "cherry"}
x = [Link]()
print(x)

apple

Note: The pop() method returns removed value.

Python Set remove() Method


Example
Remove "banana" from the set:
fruits = {"apple", "banana", "cherry"}
[Link]("banana")
print(fruits)

{'cherry', 'apple'}

Definition and Usage


The remove() method removes the specified element from the set. This
method is different from the discard() method, because
the remove() method will raise an error if the specified item does not exist,
and the discard() method will not.

Syntax
[Link](item)

Parameter Values
Parameter Description

item Required. The item to search for, and remove

36
Python Set symmetric_difference() Method
Example
Return a set that contains all items from both sets, except items that are
present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

{'banana', 'microsoft', 'google', 'cherry'}

Definition and Usage


The symmetric_difference() method returns a set that contains all items
from both set, but not the items that are present in both sets.
Meaning: The returned set contains a mix of items that are not present in
both sets.

Syntax
set.symmetric_difference(set)

Parameter Values
Parameter Description

set Required. The set to check for matches in

Python Set symmetric_difference_update() Method


Example
Remove the items that are present in both sets, AND insert the items that is
not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

{'google', 'cherry', 'microsoft', 'banana'}

Definition and Usage


The symmetric_difference_update() method updates the original set by
removing items that are present in both sets, and inserting the other items.

37
Syntax
set.symmetric_difference_update(set)

Parameter Values
Parameter Description

set Required. The set to check for matches in

Python Set union() Method


Example
Return a set that contains all items from both sets, duplicates are excluded:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
{'cherry', 'microsoft', 'apple', 'banana', 'google'}

Definition and Usage


The union() method returns a set that contains all items from the original set,
and all items from the specified set(s). You can specify as many sets you want,
separated by commas. It does not have to be a set, it can be any iterable
object. If an item is present in more than one set, the result will contain only
one appearance of this item.

Syntax
[Link](set1, set2...)

Parameter Values
Parameter Description

set1 Required. The iterable to unify with

set2 Optional. The other iterable to unify with.


You can compare as many iterables as you like.
Separate each iterable with a comma

More Examples
Example
Unify more than 2 sets:

38
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
result = [Link](y, z)
print(result)

{'f', 'b', 'd', 'e', 'c', 'a'}

Python Set update() Method


Example
Insert the items from set y into set x:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
[Link](y)
print(x)

{'cherry', 'google', 'apple', 'banana', 'microsoft'}

Definition and Usage


The update() method updates the current set, by adding items from another
set (or any other iterable). If an item is present in both sets, only one
appearance of this item will be present in the updated set.

Syntax
[Link](set)

Parameter Values
Parameter Description

set Required. The iterable insert into the current set

Python - Set Exercises


Test Yourself With Exercises
Now you have learned a lot about sets, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:

Exercise:
Check if "apple" is present in the fruits set.

39
fruits = {"apple", "banana", "cherry"}
if "apple" fruits:
print("Yes, apple is a fruit!")

Exercise:
Use the add method to add "orange" to the fruits set.
fruits = {"apple", "banana", "cherry"}

Exercise:
Use the correct method to add multiple items (more_fruits) to
the fruits set.
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]

Exercise:
Use the remove method to remove "banana" from the fruits set.
fruits = {"apple", "banana", "cherry"}

Exercise:
Use the discard method to remove "banana" from the fruits set.
fruits = {"apple", "banana", "cherry"}

Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary
Dictionaries are used to store data values in key:value pairs. A dictionary is a
collection which is ordered*, changeable and do not allow duplicates.

40
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

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

Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ford

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove
items after the dictionary has been created.

41
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Length
To determine how many items a dictionary has, use the len() function:

Example
Print the number of items in the dictionary:
print(len(thisdict))
3

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors':
['red', 'white', 'blue']}

type()
From Python's perspective, dictionaries are defined as objects with the data
type 'dict':
<class 'dict'>

42
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
<class 'dict'>

Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever
you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of


that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.

Python - Access Dictionary


Items
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",

43
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang

There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:
x = [Link]("model")
print(x)
Mustang

Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = [Link]()
print(x)
dict_keys(['brand', 'model', 'year'])

The list of the keys is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the keys list.

Example
Add a new item to the original dictionary, and see that the keys list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])

44
Get Values
The values() method will return a list of all the values in the dictionary.

Example
Get a list of the values:
x = [Link]()
print(x)
dict_values(['Ford', 'Mustang', 1964])

The list of the values is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the values list.

Example
Make a change in the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])

Example
Add a new item to the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])

45
Get Items
The items() method will return each item in a dictionary, as tuples in a list.

Example
Get a list of the key:value pairs
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])

The returned list is a view of the items of the dictionary, meaning that any
changes done to the dictionary will be reflected in the items list.

Example
Make a change in the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
2020)])

Example
Add a new item to the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()

46
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964), ('color', 'red')])

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Yes, 'model' is one of the keys in the thisdict dictionary

Python - Change Dictionary


Items
Change Values
You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

47
Update Dictionary
The update() method will update the dictionary with the items from the
given argument.
The argument must be a dictionary, or an iterable object with key:value
pairs.

Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Python - Add Dictionary Items


Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'red'}

Update Dictionary
The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value
pairs.

48
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'red'}

Python - Remove Dictionary


Items
Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}

Example
The popitem() method removes the last inserted item (in versions before
3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}

49
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}

Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no
longer exists.
Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in <module>
print(thisdict) #this will cause an error because "thisdict"
no longer exists.
NameError: name 'thisdict' is not defined

Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{}

Python - Loop Dictionaries


Loop Through a Dictionary
You can loop through a dictionary by using a for loop.

50
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.

Example
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
brand
model
year

Example
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Ford
Mustang
1964

Example
You can also use the values() method to return values of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
Ford
Mustang
1964

Example
You can use the keys() method to return the keys of a dictionary:

51
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
brand
model
year
Example
Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in [Link]():
print(x, y)

brand Ford
model Mustang
year 1964

Python - Copy Dictionaries


Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2. There are ways to make a
copy, one way is to use the built-in Dictionary method copy().

Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)

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

Another way to make a copy is to use the built-in function dict().

52
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

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

Python - Nested Dictionaries


Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.

Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name':
'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year':
2011}}

Or, if you want to add three dictionaries into a new dictionary:

53
Example
Create three dictionaries, then create one dictionary that will contain the
other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name':
'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year':
2011}}

Python Dictionary Methods


Python has a set of built-in methods that you can use on dictionaries.

Method Description

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

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

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

54
pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value

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

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

Python Dictionary clear() Method


Example
Remove all elements from the car list:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(car)
{}

Definition and Usage


The clear() method removes all the elements from a dictionary.

Syntax
[Link]()

Parameter Values
No parameters

Python Dictionary copy() Method


Example
Copy the car dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

55
x = [Link]()
print(x)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Definition and Usage


The copy() method returns a copy of the specified dictionary.

Syntax
[Link]()

Parameter Values
No parameters

Python Dictionary fromkeys() Method


Example
Create a dictionary with 3 keys, all with the value 0:
x = ('key1', 'key2', 'key3')
y = 0
thisdict = [Link](x, y)
print(thisdict)
['key1': 0, 'key2': 0, 'key3': 0]

Definition and Usage


The fromkeys() method returns a dictionary with the specified keys and the
specified value.

Syntax
[Link](keys, value)

Parameter Values
Parameter Description

keys Required. An iterable specifying the keys of the new


dictionary

value Optional. The value for all keys. Default value is None

56
More Examples
Example
Same example as above, but without specifying the value:
x = ('key1', 'key2', 'key3')
thisdict = [Link](x)
print(thisdict)
['key1': None, 'key2': None, 'key3': None]

Python Dictionary get() Method


Example
Get the value of the "model" item:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("model")

print(x)
Mustang

Definition and Usage


The get() method returns the value of the item with the specified key.

Syntax
[Link](keyname, value)

Parameter Values
Parameter Description

keyname Required. The keyname of the item you want to


return the value from

value Optional. A value to return if the specified key does


not exist.
Default value None

57
More Examples
Example
Try to return the value of an item that do not exist:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("price", 15000)

print(x)
15000

Python Dictionary items() Method


Example
Return the dictionary's key-value pairs:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])

Definition and Usage


The items() method returns a view object. The view object contains the key-
value pairs of the dictionary, as tuples in a list.
The view object will reflect any changes done to the dictionary, see example
below.

Syntax
[Link]()

Parameter Values
No parameters

58
More Examples
Example
When an item in the dictionary changes value, the view object also gets
updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()
car["year"] = 2018
print(x)

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',


2018)])

Python Dictionary keys() Method


Example
Return the keys:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)

dict_keys(['brand', 'model', 'year'])

Definition and Usage


The keys() method returns a view object. The view object contains the keys
of the dictionary, as a list.
The view object will reflect any changes done to the dictionary, see example
below.

Syntax
[Link]()

59
Parameter Values
No parameters

More Examples
Example
When an item is added in the dictionary, the view object also gets updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()
car["color"] = "white"
print(x)

dict_keys(['brand', 'model', 'year', 'color'])

Python Dictionary pop() Method


Example
Remove "model" from the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(car)
{'brand': 'Ford', 'year': 1964}

Definition and Usage


The pop() method removes the specified item from the dictionary.
The value of the removed item is the return value of the pop() method, see
example below.

Syntax
[Link](keyname, defaultvalue)

60
Parameter Values
Parameter Description

keyname Required. The keyname of the item you want to


remove

defaultvalue Optional. A value to return if the specified key do


not exist.

If this parameter is not specified, and the no item


with the specified key is found, an error is raised

More Examples
Example
The value of the removed item is the return value of the pop() method:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("model")
print(x)
Mustang

Python Dictionary popitem() Method


Example
Remove the last item from the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(car)

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

Definition and Usage


The popitem() method removes the item that was last inserted into the
dictionary. In versions before 3.7, the popitem() method removes a random
item.

61
The removed item is the return value of the popitem() method, as a tuple,
see example below.

Syntax
[Link]()

Parameter Values
No parameters

More Examples
Example
The removed item is the return value of the pop() method:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
('year', 1964)

Python Dictionary setdefault() Method


Example
Get the value of the "model" item:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("model", "Bronco")

print(x)
Mustang

Definition and Usage


The setdefault() method returns the value of the item with the specified
key.
If the key does not exist, insert the key, with the specified value, see
example below

62
Syntax
[Link](keyname, value)

Parameter Values
Parameter Description

keyname Required. The keyname of the item you want to return


the value from

value Optional.
If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's
value
Default value None

More Examples
Example
Get the value of the "color" item, if the "color" item does not exist, insert
"color" with the value "white":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("color", "white")
print(x)
White

Python Dictionary update() Method


Example
Insert an item to the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

63
[Link]({"color": "White"})

print(car)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'White'}

Definition and Usage


The update() method inserts the specified items to the dictionary.
The specified items can be a dictionary, or an iterable object with key value
pairs.

Syntax
[Link](iterable)

Parameter Values
Parameter Description

iterable A dictionary or an iterable object with key value pairs,


that will be inserted to the dictionary

Python Dictionary values() Method


Example
Return the values:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)

dict_values(['Ford', 'Mustang', 1964])

Definition and Usage


The values() method returns a view object. The view object contains the
values of the dictionary, as a list.
The view object will reflect any changes done to the dictionary, see example
below.

64
Syntax
[Link]()

Parameter Values
No parameters

More Examples
Example
When a values is changed in the dictionary, the view object also gets
updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
car["year"] = 2018
print(x)

dict_values(['Ford', 'Mustang', 2018])

Python Dictionary Exercises


Test Yourself With Exercises
Now you have learned a lot about dictionaries, and how to use them in
Python.

Are you ready for a test?

Try to insert the missing part to make the code work as expected:

Exercise:
Use the get method to print the value of the "model" key of
the car dictionary.

car = {
"brand": "Ford",

65
"model": "Mustang",
"year": 1964
}
print( )

Exercise:
Change the "year" value from 1964 to 2020.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
=

Exercise:
Use the pop method to remove "model" from the car dictionary.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Exercise:
Use the clear method to empty the car dictionary.

car = {
"brand": "Ford",
"model": "Mustang",
66
"year": 1964
}

Python If ... Else


Python Conditions and If statements
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
These conditions can be used in several ways, most commonly in "if
statements" and loops. An "if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
b is greater than a

In this example we use two variables, a and b, which are used as part of the
if statement to test whether b is greater than a. As a is 33, and b is 200, we
know that 200 is greater than 33, and so we print to screen that "b is greater
than a".

Indentation
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.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
File "demo_if_error.py", line 4
print("b is greater than a")

67
^
IndentationError: expected an indented block

Elif
The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".

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

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

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

Example
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")

a is greater than b

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".

You can also have an else without the elif:

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

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

Example
One line if statement:
if a > b: print("a is greater than b")
"a is greater than b"

Short Hand If ... Else


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

Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
B
This technique is known as Ternary Operators, or Conditional
Expressions.

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
=

69
And
The and keyword is a logical operator, and is used to combine conditional
statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Both conditions are True

Or
The or keyword is a logical operator, and is used to combine conditional
statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True

Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Above ten,
and also above 20!

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.

70
Example
a = 33
b = 200

if b > a:
pass

Exercise:
Print "Hello World" if a is greater than b.
a = 50
b = 10
a b
print("Hello World")

Exercise:
Print "Hello World" if a is not equal to b.
a = 50
b = 10
a b
print("Hello World")

Exercise:
Print "Yes" if a is equal to b, otherwise print "No".
a = 50
b = 10
a b
print("Yes")

print("No")

Exercise:
Print "1" if a is equal to b, print "2" if a is greater than b, otherwise print "3".
a = 50
b = 10

71
a b
print("1")
a b
print("2")

print("3")

Exercise:
Print "Hello" if a is equal to b, and c is equal to d.
if a == b c == d:
print("Hello")

Exercise:
Print "Hello" if a is equal to b, or if c is equal to d.
if a == b c == d:
print("Hello")

Exercise:
This example misses indentations to be correct.
Insert the missing indentation to make the code correct:
if 5 > 2:
print("Five is greater than two!")

Exercise:
Use the correct short hand syntax to put the following statement on one line:
if 5 > 2:
print("Five is greater than two!")

Exercise:
Use the correct short hand syntax to write the following conditional
expression in one line:

72
if 5 > 2:
print("Yes")
else
print("No")

Python While Loops


Python Loops
Python has two primitive loop commands:
• while loops
• for loops

The while Loop


With the while loop we can execute a set of statements as long as a
condition is true.
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
1
2
3
4
5

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

The while loop requires relevant variables to be ready, in this example we


need to define an indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is
true:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:

73
break
i += 1
1
2
3

The continue Statement


With the continue statement we can stop the current iteration, and continue
with the next:
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3: # Note that number 3 is missing in the result
continue
print(i)
1
2
4
5
6

The else Statement


With the else statement we can run a block of code once when the condition
no longer is true:
Example
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1
2
3
4
5
i is no longer less than 6

74
Exercise:
Print i as long as i is less than 6.
i = 1
i < 6
print(i)
i += 1

Exercise:
Stop the loop if i is 3.
i = 1
while i < 6:
if i == 3:

i += 1

Exercise:
In the loop, when i is 3, jump directly to the next iteration.
i = 0
while i < 6:
i += 1
if i == 3:

print(i)

Exercise:
Print a message once the condition is false.
i = 1
while i < 6:
print(i)
i += 1

print("i is no longer less than 6")

75
Python For Loops
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). This is less like the for keyword in other
programming languages, and works more like an iterator method as found in
other object-orientated programming languages. With the for loop we can
execute a set of statements, once for each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple
banana
cherry

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
b
a
n
a
n
a

The break Statement


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

Example
Exit the loop when x is "banana":

76
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
apple
banana

Example
Exit the loop when x is "banana", but this time the break comes before the
print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
apple

The continue Statement


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

Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
apple
cherry

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.
Example
Using the range() function:
for x in range(6):
print(x)
0
1
2
3

77
4
5
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):

Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
2
5
8
11
14
17
20
23
26
29

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
0
1
2
3
4
5
Finally finished!
Note: The else block will NOT be executed if the loop is stopped by
a break statement.

Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

78
0
1
2

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":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

ed apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

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.
Example
for x in [0, 1, 2]:
pass

Exercise:
Loop through the items in the fruits list.

fruits = ["apple", "banana", "cherry"]


x fruits
print(x)

79
Exercise:
In the loop, when the item value is "banana", jump directly to the next item.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":

print(x)

Exercise:
Use the range function to loop through a code set 6 times.
for x in :
print(x)

Exercise:
Exit the loop when x is "banana".
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":

print(x)

Python Functions
A function is a block of code which only runs when it is called. You can
pass data, known as parameters, into a function. A function can return
data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

80
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()

Hello from a function

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")

Emil Refsnes
Tobias Refsnes
Linus Refsnes

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:


A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.

81
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")
Emil Refsnes

If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional argument:
'lname'

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter
name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


The youngest child is Linus

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.

82
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The youngest child is Linus

The phrase Keyword Arguments are often shortened to kwargs in Python


documentations.

Arbitrary Keyword Arguments,


**kwargs
If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")

His last name is Refsnes

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

Default Parameter Value


The following example shows how to use a default parameter value. If we
call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

83
I am from Sweden
I am from India
I am from Norway
I am from Brazil

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function. E.g. if you send a List as an argument, it will still be a List when it
reaches the function:

Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
apple
banana
cherry

Return Values
To let a function, return a value, use the return statement:

Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
15
25
45

The pass Statement


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

Example
def myfunction():
pass

84
Recursion
Python also accepts function recursion, which means a defined function can
call itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.

Example
Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)
Recursion Example Results
1
3
6
10
15
21

85
Exercise:
Create a function named my_function.
:
print("Hello from a function")

Exercise:
Execute a function named my_function.
def my_function():
print("Hello from a function")

Exercise:
Inside a function with two parameters, print the first parameter.
def my_function(fname, lname):
print( )

Exercise:
Let the function return the x parameter + 5.
def my_function(x):

Exercise:
If you do not know the number of arguments that will be passed into your
function, there is a prefix you can add in the function definition, which prefix?
def my_function( kids):
print("The youngest child is " + kids[2])

Exercise:
If you do not know the number of keyword arguments that will be passed
into your function, there is a prefix you can add in the function definition,
which prefix?
def my_function( kid):
print("His last name is " + kid["lname"])

86
Python Lambda
A lambda function is a small anonymous function. A lambda function can
take any number of arguments, but can only have one expression.

Syntax
lambda arguments : expression
The expression is executed and the result is returned:

Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
15
Lambda functions can take any number of arguments:

Example
Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))
30

Example
Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
13

Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous
function inside another function. Say you have a function definition that
takes one argument, and that argument will be multiplied with an unknown
number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the
number you send in:

87
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

22
Or, use the same function definition to make a function that
always triples the number you send in:

Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))

33

Or, use the same function definition to make both functions, in the same
program:

def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))

22
33

Use lambda functions when an anonymous function is required for a short


period of time.

Exercise:
Create a lambda function that takes one parameter (a) and returns it.
x =

88
Python Arrays
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work
with arrays in Python you will have to import a library, like the NumPy
library.

Arrays are used to store multiple values in one single variable:

Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
print(cars)
['Ford', 'Volvo', 'BMW']

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.

Note: Python does not have built-in support for Arrays, but Python Lists can
be used instead. Thus, for python array len property and other methods of
python array, one can always refer the python list method discussed in the
preceding topics.

Python Classes and Objects


Python Classes/Objects
Python is an object-oriented programming language. Almost everything in
Python is an object, with its properties and methods. A Class is like an object
constructor, or a "blueprint" for creating objects.

89
Create a Class
To create a class, use the keyword class:

Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
print(mydoubler(11))

<class '__main__.MyClass'>

Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
5

The __init__() Function


The examples above are classes and objects in their simplest form, and are
not really useful in real life applications.

To understand the meaning of classes we have to understand the built-in


__init__() function.

All classes have a function called __init__(), which is always executed when
the class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

90
p1 = Person("John", 36)

print([Link])
print([Link])

John
36

Note: The __init__() function is called automatically every time the class is
being used to create a new object.

The __str__() Function


The __str__() function controls what should be returned when the class
object is represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:

Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print(p1)

<__main__.Person object at 0x15039e602100>

Example
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def __str__(self):
return f"{[Link]}({[Link]})"
p1 = Person("John", 36)
print(p1)

John(36)

91
Object Methods
Objects can also contain methods. Methods in objects are functions that
belong to the object. Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()

Hello my name is John

Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.

The self Parameter


The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it
has to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
[Link] = name
[Link] = age
def myfunc(abc):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()

Hello my name is John

Modify Object Properties


You can modify properties on objects like this:

92
Example
Set the age of p1 to 40:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link] = 40
print([Link])
40

Delete Object Properties


You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
del [Link]
print([Link])
Traceback (most recent call last):
File "demo_class7.py", line 13, in <module>
print([Link])
AttributeError: 'Person' object has no attribute 'age'

Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
del p1

93
print(p1)
Traceback (most recent call last):
File "demo_class8.py", line 13, in <module>
print(p1)
NameError: 'p1' is not defined

The pass Statement


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

Example
class Person:
pass

Exercise:
Create a class named MyClass:

MyClass:
x = 5

Exercise:
Create an object of MyClass called p1:

class MyClass:
x = 5
=

Exercise:
Use the p1 object to print the value of x:

class MyClass:
x = 5
p1 = MyClass()
print( )

94
Exercise:
What is the correct syntax to assign a "init" function to a class?

class Person:
def (self, name, age):
[Link] = name
[Link] = age

Python Inheritance
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived
class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any
other class:

Example
Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

#Use the Person class to create an object, and then execute the
printname method:

95
x = Person("John", "Doe")
[Link]()

John Doe

Create a Child Class


To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:

Example
Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other
properties or methods to the class.

Now the Student class has the same properties and methods as the Person
class.

Example
Use the Student class to create an object, and then execute
the printname method:

class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
pass

x = Student("Mike", "Olsen")
[Link]()

Mike Olsen

96
Add the __init__() Function
So far we have created a child class that inherits the properties and methods
from its parent.

We want to add the __init__() function to the child class (instead of


the pass keyword).

Note: The __init__() function is called automatically every time the class is
being used to create a new object.

Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

x = Student("Mike", "Olsen")
[Link]()
Mike Olsen

Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.

97
Use the super() Function
Python also has a super() function that will make the child class inherit all
the methods and properties from its parent:
Example
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

x = Student("Mike", "Olsen")
[Link]()

Mike Olsen

By using the super() function, you do not have to use the name of the
parent element, it will automatically inherit the methods and properties from
its parent.

Add Properties
Example
Add a property called graduationyear to the Student class:

class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019

x = Student("Mike", "Olsen")
print([Link])

98
2019

In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

x = Student("Mike", "Olsen", 2019)


print([Link])
2019

Add Methods
Example
Add a method called welcome to the Student class:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

def welcome(self):
print("Welcome", [Link], [Link], "to the class
of", [Link])
x = Student("Mike", "Olsen", 2019)
[Link]()

99
Welcome Mike Olsen to the class of 2019

If you add a method in the child class with the same name as a function in
the parent class, the inheritance of the parent method will be overridden.

Exercise:
What is the correct syntax to create a class named Student that will inherit
properties and methods from a class named Person?
class :

Exercise:
We have used the Student class to create an object named x.
What is the correct syntax to execute the printname method of the object x?
class Person:
def __init__(self, fname):
[Link] = fname

def printname(self):
print([Link])

class Student(Person):
pass

x = Student("Mike")

Python Iterators
Python Iterators
An iterator is an object that contains a countable number of values. An
iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods __iter__() and __next__().

100
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from. All these objects have
a iter() method which is used to get an iterator:

Example
Return an iterator from a tuple, and print each value:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))

apple
banana
cherry

Even strings are iterable objects, and can return an iterator:

Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

b
a
n
a
n
a

Looping Through an Iterator


We can also use a for loop to iterate through an iterable object:

101
Example
Iterate the values of a tuple:
mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)

apple
banana
cherry

Example
Iterate the characters of a string:

mystr = "banana"

for x in mystr:
print(x)
b
a
n
a
n
a

The for loop actually creates an iterator object and executes the next()
method for each loop.

Create an Iterator
To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.

As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you to do some initializing when the
object is being created.

The __iter__() method acts similar, you can do operations (initializing etc.),
but must always return the iterator object itself.

The __next__() method also allows you to do operations, and must return the
next item in the sequence.

102
Example
Create an iterator that returns numbers, starting with 1, and each sequence
will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

1
2
3
4
5

StopIteration
The example above would continue forever if you had enough next()
statements, or if it was used in a for loop.

To prevent the iteration to go on forever, we can use


the StopIteration statement.

In the __next__() method, we can add a terminating condition to raise an


error if the iteration is done a specified number of times:

Example
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self

103
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Python Scope
A variable is only available from inside the region it is created. This is
called scope.

Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.

104
Example
A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

300

Function Inside Function


As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()

300

Global Scope
A variable created in the main body of the Python code is a global variable
and belongs to the global scope. Global variables are available from within
any scope, global and local.

Example
A variable created outside of a function is global and can be used by anyone:

x = 300
def myfunc():
print(x)

myfunc()
print(x)

105
300
300

Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):

Example
The function will print the local x, and then the code will print the global x:

x = 300
def myfunc():
x = 200
print(x)

myfunc()
print(x)

200
300

Global Keyword
If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword. The global keyword makes the variable global.

Example
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = 300

myfunc()
print(x)

300

Also, use the global keyword if you want to make a change to a global
variable inside a function.

106
Example
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:

x = 300
def myfunc():
global x
x = 200

myfunc()
print(x)

200

Python Modules
What is a Module?
Consider a module to be the same as a code library. A file containing a set of
functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file
extension .py:

Example
Save this code in a file named [Link]
def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule
[Link]("Jonathan")

Hello, Jonathan

Note: When using a function from a module, use the


syntax: module_name.function_name.

107
Variables in Module
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):

Example
Save this code in the file [Link]
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule
a = mymodule.person1["age"]
print(a)

36

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx
a = mx.person1["age"]
print(a)

36

Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.

108
Example
Import and use the platform module:

import platform
x = [Link]()
print(x)

Windows

Using the dir() Function


There is a built-in function to list all the function names (or variable names)
in a module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform
x = dir(platform)
print(x)

['DEV_NULL', '_UNIXCONFDIR', 'WIN32_CLIENT_RELEASES',


'WIN32_SERVER_RELEASES', '__builtins__', '__cached__',
'__copyright__', '__doc__', '__file__', '__loader__', '__name__',
'__package __', '__spec__', '__version__',
'_default_architecture', '_dist_try_harder', '_follow_symlinks',
'_ironpython26_sys_version_parser',
'_ironpython_sys_version_parser', '_java_getprop',
'_libc_search', '_linux_distribution', '_lsb_release_version',
'_mac_ver_xml', '_node', '_norm_version', '_perse_release_file',
'_platform', '_platform_cache', '_pypy_sys_version_parser',
'_release_filename', '_release_version', '_supported_dists',
'_sys_version', '_sys_version_cache', '_sys_version_parser',
'_syscmd_file', '_syscmd_uname', '_syscmd_ver', '_uname_cache',
'_ver_output', 'architecture', 'collections', 'dist', 'java_ver',
'libc_ver', 'linux_distribution', 'mac_ver', 'machine', 'node',
'os', 'platform', 'popen', 'processor', 'python_branch',
'python_build', 'python_compiler', 'python_implementation',
'python_revision', 'python_version', 'python_version_tuple',
're', 'release', 'subprocess', 'sys', 'system', 'system_aliases',
'uname', 'uname_result', 'version', 'warnings', 'win32_ver']

Note: The dir() function can be used on all modules, also the ones you
create yourself.

109
Import From Module
You can choose to import only parts from a module, by using
the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:

from mymodule import person1


print (person1["age"])
36

Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]

Exercise:
What is the correct syntax to import a module named "mymodule"?

mymodule

Exercise:
If you want to refer to a module by using a different name, you can create an
alias. What is the correct syntax for creating an alias for a module?

import mymodule mx

Exercise:
What is the correct syntax of printing all variables and function names of the
"mymodule" module?

110
import mymodule
print( )

Exercise:
What is the correct syntax of importing only the person1 dictionary of the
"mymodule" module?

mymodule person1

111

You might also like