Introduction To Python Course Manual 65636f2ca569c
Introduction To Python Course Manual 65636f2ca569c
v W W W. W A L L S T R E E T P R E P. C O M
Intro to Python for Financial Services
Course Overview
1 2
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What this course is about…
à you will have the knowledge and understanding to learn more on your own
à numerical computations
à charting
3
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Content Overview
à installing and running Python
4
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Content Overview
à functional programming functions
higher-order functions
closures
decorators
5
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Content Overview
6
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Prerequisites
à Windows, Mac
à needs to run Python 3.6+ (recommend at least 3.8/3.9 or higher)
Windows 10 Mac 10.9 and higher
à Linux – you'll need to find/use installation instructions
à exercises
à each section (except installation section) has a set of exercises
à make sure you are confident before moving on to the next section
Installing and
Running Python
2 9
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à what is Python?
à language vs implementation
à installing Python
à side by side versions of Python
à virtual environments
10
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Python
11
FooterLicensed to Kevin Romanteau. Email address: [email protected]
A bit of history…
12
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What is Python?
à Python is a language, not an application
à there are many implementations of Python
CPython
PyPy
à even compilers that "translate" Python code to other languages
IronPython à .NET
Jython à Java
Cython à C/C++
13
FooterLicensed to Kevin Romanteau. Email address: [email protected]
CPython
à reference implementation à https://www.python.org
à most widely used distribution of Python
à open source à written in C https://github.com/python/cpython
à includes the standard library
à a collection of additional functionality that goes beyond
just the Python language
à written in C and Python
à many platforms Linux, Windows, Mac OS, iOS, Android, PlayStation, Xbox,…
14
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Installing Python
15
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Installing CPython
à CPython is basically a bunch of files, located in some directory on your
computer
à one of those files is an executable that is used to run Python code
files or an interactive shell
à entire standard library is also included in these files
16
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Where to find installation packages
à https://www.python.org
17
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à choose which version you want and what OS you are on
18
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à two videos included in this course
à Windows Installation
à Mac Installation
(Linux installation is same as Mac, just download for Linux OS)
19
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Virtual Environments
20
FooterLicensed to Kevin Romanteau. Email address: [email protected]
3rd Party Libraries
à many 3rd party libraries exist
à add-ons to Python for more specialized functionality
à a bunch of files
à that get added to your Python "installation"
21
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Solution
à since Python is just a directory of files
à create two copies of this directory
/usr/user1/python3.9-ENV1/ /usr/user1/python3.9-ENV2/
install some_lib_1.0 in here install some_lib_1.1 in here
à /Users/user1/python3.9-ENV1/bin/python my_app.py
à /Users/user1/python3.9-ENV2/bin/python my_other_app.py
22
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Solution
/usr/user1/python3.9-ENV1/
à add /usr/user1/python3.9-ENV1/ to (front of) PATH
à python my_app.py
/usr/user1/python3.9-ENV2/
23
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Virtual Environments
à these are used to perform the exact same steps
à make copy of Python installation
à provides scripts to "activate"/"deactivate" the environment
à unsets old path / sets new path
24
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Creating Virtual Environments
à different implementations of this have evolved over the years
25
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Activating the Virtual Environment
Windows: <path_to_env>\Scripts\activate.bat
26
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
27
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Installing Packages
28
FooterLicensed to Kevin Romanteau. Email address: [email protected]
pip: Package Installer for Python
29
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Installing Packages with pip
à activate the virtual environment first (sets your PATH)
à pip install package_name
à can even specify versions
pip install package_name==1.3.2
30
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The requirements.txt File
à use a file, alongside your code, to keep track of required packages and versions
requirements.txt
numpy==1.18.1 à file name can be anything
pandas==1.1.4 à requirements.txt is a standard
matplotlib==3.3.3 convention
31
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à for this course a requirements.txt file is available in your downloads
32
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Summary of Steps
33
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
34
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Running Python
35
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Python Compiler/Interpreter
Intermediate
Python Python
Code
code compiler
(bytecode)
Virtual
Machine
à Python is both a compiler (OS/Platform
specific)
and an interpreter
Operating
System
36
FooterLicensed to Kevin Romanteau. Email address: [email protected]
How do we "run" Python?
à Python is a compiler/interpreter
à reads in a chunk of code (your program)
à compiles and runs it
à output is sent to your screen (console)
à Python can do this in two ways
à interactive mode
à you type a Python line/block of code and execute it immediately
à any output is immediately displayed
à continue typing/running code one line/block at a time
à REPL (read-eval-print-loop)
à script mode
à write all your code in files first
à then execute all this code using command line
37
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Interactive Mode
à activate virtual environment
à start Python shell (REPL) by typing python on command line
à start typing Python commands
à non graphical interface
à perfect when working on GUI-less servers
à little tedious to use when you are just trying things out
à Jupyter Notebooks
à browser based REPL (needs to be pip installed)
à much easier/nicer to use than command line
à can save your projects into a file (a notebook)
à usually .ipynb extension
38
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Script Mode
à write all your code using a text editor
39
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Python IDEs
IDE à integrated development environment
à a text editor
à with many extras for easily running code, debugging, and more
à runs code using the same command line approach for scripts
à Atom
à Sublime Text 3
à Spyder and more…
40
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
41
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Python Basics
3 42
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à some basic Python types
à integers à floats à booleans
à basic operators
à arithmetic operators
à integer division and modulus
à comparison operators
à Boolean operators
à operator precedence
43
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Basic Data Types
44
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Types
à Entities in a program always have an associated type
à in the real world too!
John is a person
My local pharmacy is a store
My bank balance is a (real) number
The number of pages in a book is an (integer) number
The file budget.xlsx is an Excel spreadsheet
Statements can be True or False
they have a type à Boolean type (True, False)
"I am a Python dev" is True
"My dog likes cats" is False
45
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Integers
à the int type
à used to represent integral numbers: 0, 1, 100, -100, etc.
à integers have an exact representation in Python
à integers can be of any magnitude
(as long as you have enough memory!)
à the decimal point differentiates a float from an int when using literals
1 à int
1.0 à float
47
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Float Representations
Consider the decimal system: 1.234
In the decimal (base 10) system, this is representable (exactly) using powers of 10:
2 3 4
1+ + +
10 100 1000
1
But not all real numbers have a finite representation
3
as a fraction this is exact à but not using a decimal representation
1 3 3 3
̇
= 0.333 = + + +⋯
3 10 100 1000
49
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Float Binary Representation
in the same way, floats are represented using powers of 2 and fractions of
powers of 2
1 0 1 1 0 1
+ + = + +
2. 2/ 20 2 4 8
= 0.5 + 0 + 0.125 = 0.625
.
à we saw that certain numbers do not have a finite decimal representation ( )
0
à same happens with binary representations!
0 0 0 1 1 0 0 1 1
0.1 = + + + + + + + + + ⋯
2 4 8 16 32 64 128 256 512
0.09375
0.099609375
50
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Floats are not always exact
à bottom line: not all exact decimal numbers have an exact float representation
à there is a data type that can handle exact representations of decimal fractions
51
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
52
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Objects
53
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What are objects?
à entities created by Python
Car
State (data) Functionality
• brand à Toyota
• accelerate()
• model à Prius LE
• brake()
• # doors à 4
• set_cruise_control()
• model_year à 2020
• left_turn_signal_on()
• odometer à 5_402
54
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Integers are Objects
à an int is an object
55
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Floats are Objects
state à value
functionality à __add__
(0.125).as_integer_ratio() à 1, 8
56
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Everything in Python is an object
à it has state
attributes
à it has functionality
57
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dot Notation
If an object has attributes, how do we access those attributes?
à dot notation
58
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Mutability and Immutability
à an object is mutable if its internal state can be changed
à one or more data attributes can be changed
60
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Variables
61
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Naming Objects
apy account_balance
62
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Assigning Names
To assign a label to an object we use the assignment operator =
account_balance = 1000.0
this is not the
apy = 0.25 mathematical
equality
symbol
à we are assigning the label apy to the object 0.25
63
FooterLicensed to Kevin Romanteau. Email address: [email protected]
References and Variables
Another way of looking at this: some object in memory
float
0.25
references
the object
apr
list
a 1, 2, 3 , 4
apy = 0.25
LHS RHS
66
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Using Variables
Once a variable has been created, it can be used elsewhere in the program
pi = 3.1415 pi 3.1415
radius = 1 radius 1
radius = 2 radius 2
67
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Variable Naming
68
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Must-Follow Rules
69
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Should-Follow Conventions
https://www.python.org/dev/peps/pep-0008/
terminology:
camel case àseparate words are distinguished by upper case letters
accountBalance BankAccount
account_balance bank_account
70
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Should-Follow Conventions
For standard variables:
à snake case
à all lower case letters
account_balance ✅
account_Balance ❌
We'll see other conventions for other special types of objects throughout
this course
71
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Should-Follow Conventions
72
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
73
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Arithmetic Operators
74
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Terminology
An operator is a programming language symbol that performs some operation on
one or more values
Certain types of operators include:
à arithmetic operators
à comparison (or relational) operators
à logical operators
75
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Arithmetic Operators
Unary Operators
- Unary Minus -10
+ Unary Plus +10
Binary Operators
+ Addition 10 + 20
- Subtraction 20 - 10
* Multiplication 10 * 2
/ Division 10 / 2
** Power (exponentiation) 2 ** 4
2 + 2 à returns an int
2 + 2.0 à returns a float
5.5 * 2 à returns a float
4 / 2 à also returns a float!
77
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The Power Operator
The power operator works just like its mathematical counterpart
2 ** 4
à 2 * 2 * 2 * 2
à 16 (int)
1
Recall from math: 245 =
25
2 ** (-4)
à 1 / (2 ** 4)
à 1 / 16
à 0.0625 (float)
78
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The Power Operator
à Python supports floats for either operand of the ** operator
à just like mathematical exponentiation
à graph of 𝑓 𝑥 = 𝑒 9
à 𝑏 9 : = 𝑒 9 <=>(@)
à a.__add__(b)
à this works the same way with other types
80
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Looking ahead…
à any type can choose to implement __add__ however it wants
à Python will then use that method to evaluate type_1 + type_2
à we'll look at this in code, though some of the code may not make sense (yet!)
81
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
82
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Operator Precedence
83
FooterLicensed to Kevin Romanteau. Email address: [email protected]
When we write an expression such as this: 2 * 10 + 5
why?
à operator precedence
84
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Operators have precedence
à an operator with higher precedence will bind more tightly
à fancy way of saying it will be evaluated first
* /
unary + -
higher
** except for a unary operator to the right of **
2 * 10 + 5
* has higher precedence than +
à 2 * 10 is evaluated first
à 20 + 5 à 25
85
FooterLicensed to Kevin Romanteau. Email address: [email protected]
** has highest precedence in our previous list
2 * 2 ** 3 à 2 * (2 ** 3) à 2 * 8 à 16
-2 ** 4 à -(2 ** 4) à -16
(as opposed to (-2) ** 4 à 16)
2 ** -3 à 2 ** (-3) à 0.125
à makes sense, difficult to interpret it otherwise anyway
86
FooterLicensed to Kevin Romanteau. Email address: [email protected]
A complete list of all operator precedence in Python can be found here:
https://docs.python.org/3/reference/expressions.html#operator-precedence
à my advice
à use parentheses
à it's just a few keystrokes more and will save a lot of pain later!
87
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
88
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Integer Division and Mod
89
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Let's review long division!
43
2 is the remainder
3 131
12
11 /
131 / 3 à 43
9 0
90
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The // Operator
a // b calculates the "integer portion" of a / b
à easy to understand when a and b are positive
-3.14 3.14
-4 -3 3 4
floor(-3.14) à -4 floor(3.14) à 3
12 / 5 à 2.4 12 // 5 à 2
-12 / 5 à -2.4 -12 // 5 à -3
91
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The mod Operator
Again negative numbers complicates things a bit!
à I said you can use % to calculate the remainder of dividing a by b
à in this case, for positive integers, a and b
à a % b and the remainder of dividing a by b is the same
à intuitive for positive numbers
92
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The mod Operator
/
Let's go back to our first example 131 / 3 à 43
0
a / b = a // b + (a % b)/b
à a % b = b (a / b – a // b)
à a % b = a - b (a // b)
12 % 5 à 2 12 % -5 à -3 -12 % 5 à 3 -12 % -5 à -2
95
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Comparison Operators
96
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à also know as relational operators
97
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à int and float types are comparable to each other
10 <= 10.9 à True
5 == 5 à True 5 == 6 à False
98
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What does it mean for two objects to be equal?
99
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Identity vs Value Equality of Objects
To see if two (compatible) objects are equal in value (in some sense) à ==
à in most cases use ==
à we'll see situations where using is makes more sense
a = 1 a == b à True
b = 1.0 a is b à False
c = 1
c is c à True
d = 500 d == e à True
e = 500 but… d is e à False à d and e are not
the same objects!
100
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Identity vs Value Equality of Objects
a == b à a.__eq__(b)
103
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Boolean Operators
104
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à in Boolean algebra we only have two values: True and False
à Python syntax:
105
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The not Operator
à not simply reverses the Boolean value
Truth Table
a not a
True False
False True
106
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The and Operator
a b a and b
True True True
True False False
False True False
False False False
107
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The or Operator
a b a or b
True True True
True False True
False True True
False False False
108
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Short-Circuited Evaluation
à left and right operands are not restricted to values
à can be expressions too e.g. sin(a) > 0 and cos(a) < 0
given a value a calculate sin(a) à evaluate sin(a) > 0
à result_1
calculate cos(a) à evaluate cos(a) < 0
à result_2
evaluate result_1 and result_2
à 4 calculations plus the and operation
à but what if result_1 had been False (i.e. sin(a) was not positive)?
à recall: if a is False, then a and b is always False, no matter what b is
à irrespective of what cos(a) < 0 evaluates to, the result will always be False
à so if the left operand evaluates to False, we don't even to
calculate the right operand to get an answer à short-circuited evaluation
109
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Short-Circuited Evaluation
The same happens with a or b
if a is True, then result is True, irrespective of what b is
à Python returns True without evaluating b
à short-circuited evaluation
à can be very useful
à will see examples of this in section on conditional execution
110
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example of Short-Circuiting Usefulness
à suppose we have some trading algorithm that can calculate some buy
signal (True/False)
à the catch is that the calculation is complex and resource intensive
à in addition, we only want to place an order if the exchange is open
we could write some code to do this:
if calc_signal(symbol) and exchange_open(symbol):
buy(symbol)
112
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Conditional Execution
4 113
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à one of the fundamental constructs in programming is conditional execution
à if something is true
à run some code
à else (optionally)
114
FooterLicensed to Kevin Romanteau. Email address: [email protected]
For example, for an ATM withdrawal:
à if amount does not exceed available funds and does not exceed daily limit
à dispense cash
à print receipt
à otherwise
à deny request
à display some text on screen
à print slip containing reason
à this is the primary reason we studied conditional expressions in the last chapter!
115
FooterLicensed to Kevin Romanteau. Email address: [email protected]
if… else…
116
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The if Statement
note the colon!
if <expression evaluates to True>:
code line 1
code line 2 notice how this code block is indented
…
à this tells Python that all these lines should
be executed if the condition is True
à if you are familiar with other languages such as Java or C/C++, this is
equivalent to using braces {} 117
price = 300
if price < 250:
make_purchase()
118
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Beware!
à unindenting code from a block, "exits" the block
à the following is a common mistake
price = 150
if price < 100:
this is the
print('price is below 100, buying…')
code block
make_purchase()
119
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The else Clause
à often in conditional execution
if something is True
à do something
otherwise
à do something else
122
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Nested if Statements
123
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Nested if Statements
à the nesting can occur in the else block too
124
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
125
FooterLicensed to Kevin Romanteau. Email address: [email protected]
elif
126
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Multi-Level if Statements
Consider this example to calculate a grade letter given a numeric grade:
129
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
130
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Ternary Conditional Operator
131
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Terminology
all we've done here is split the name of the operator into two
and added the operands in between
133
FooterLicensed to Kevin Romanteau. Email address: [email protected]
This type of conditional code is often used
if <conditional exp>:
var = value1
else:
var = value2
134
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The conditional ternary operator
à remember that an operator operates on operands and returns
(calculates) some result
if <conditional exp>:
var = value1
else:
var = value2
135
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The conditional ternary operator
if <conditional exp>:
var = value1
else:
var = value2
136
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
137
FooterLicensed to Kevin Romanteau. Email address: [email protected]
General Form
138
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Short-Circuiting
Just like we saw with Boolean operators, the ternary operator also uses
short-circuit evaluation
139
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
result = a / b if b != 0 else 'NaN'
a = 10 à returns 2
b = 5 à b is 5, so b != 0 evaluates to True
à a / b is calculated and returned
140
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
141
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Sequence Types
5 142
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What are Sequences?
à sequences are ordered collections of objects
à there is a first element
à there is a second element
à and a next one à sometimes called the sequential order
143
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Indexing Sequences
n objects à length of sequence
à n objects in sequence
à last element index is n-1
in this course:
à first element refers to the element at index 0
à second element refers to the element as index 1
à last element refers to the element at index n-1 (assuming n elements in sequence)
144
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sequence Length
à first element
à last element
à finite length
145
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Homogeneous vs Heterogeneous Sequences
certain sequence types can only contain objects that are all the same type
à homogeneous sequence types
other types of sequences may contain objects that are of different type
146
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sequence Types in this Chapter
147
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Lists
148
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The list Type
à it is a container type à it contains elements
149
FooterLicensed to Kevin Romanteau. Email address: [email protected]
list Literals
à Python lists can be created using literals
[10, 20, 30, 40]
Trying to access a list by index greater than last index will cause an exception!
⚠
l[5] à IndexError
151
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sequence Length
len(l) à 5
len([True, False]) à 2
152
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Empty Lists
sometimes we want to start with an empty list
and have code that adds to the list as our program runs
l = []
then len(l) à 0
⚠ l[0] à IndexError
153
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Replacing a list Element
l = [10, 20, 30, 40, 50]
à we can retrieve elements by index
print(l[2]) à 30
à but we can also replace an element at index i with a different element
à we use the assignment operator =
l[2] = True
l = [10, 20, True, 40, 50]
print(l[2]) à True
155
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Tuples
156
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The tuple Type
à very similar to the list type
à it is a container type
à it is a sequence type
157
FooterLicensed to Kevin Romanteau. Email address: [email protected]
tuple Literals
à Python tuples can be created using literals
(10, 20, 30, 40)
note the enclosing round brackets ()
à this indicates the collection is a tuple
à just like lists, they can can contain any object, including another tuple
158
FooterLicensed to Kevin Romanteau. Email address: [email protected]
tuple Literals
à often we don't even need the ()
à Python interprets a comma separated list of elements as a tuple
à so we can write (10, 20, 30)
à or just 10, 20, 30
159
FooterLicensed to Kevin Romanteau. Email address: [email protected]
tuple Literals
à just like lists, tuples can contain any object
à including other tuples or lists
list tuple
tuple
len(t) à 5
t[0] à 10
t[2] à 30
t[5] à IndexError
161
FooterLicensed to Kevin Romanteau. Email address: [email protected]
tuples are Immutable
162
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Creating Empty tuples
t = ()
163
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
164
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Strings
165
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The str Type
à it is a sequence type
166
FooterLicensed to Kevin Romanteau. Email address: [email protected]
str Literals
'this is a string'
note the enclosing quotes '…'
à can also use double quotes
"this is a string"
167
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Indexing, Length
s = 'Python'
len(s) à 6
168
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
169
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Slicing
170
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à slicing is a way to extract ranges of elements from a sequence
[start:stop]
171
FooterLicensed to Kevin Romanteau. Email address: [email protected]
l = [10, 20, 30, 40]
0 1 2 3
s = 'Isaac Newton'
0 1 2 3 4 5 6 7 8 9 10 11
s[0:4] à 'Isaa'
s[0:5] à 'Isaac'
s[6:9] à 'New'
173
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Including Last Element in Slice
s = 'Isaac Newton' s[6:11] à 'Newto'
0 1 2 3 4 5 6 7 8 9 10 11
s[6:12] à 'Newton'
s[6:1000] à 'Newton'
174
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Including First Element in a Slice
s = 'Isaac Newton'
0 1 2 3 4 5 6 7 8 9 10 11
s[:5] à 'Isaac'
175
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Slicing with Steps
à a step is a way to specify an interval when slicing a sequence
s[start:stop:step]
2 3 4 5 6 7 8 9 à indexes: 2 4 6 8
l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
0 1 2 3 4 5 6 7 8 9
176
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Negative Steps
à possible to use negative step values
l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
0 1 2 3 4 5 6 7 8 9
s = 'Isaac Newton'
0 1 2 3 4 5 6 7 8 9 10 11
s[11:5:-1] à 'notweN'
s[:5:-1] à 'notweN'
s[10::-2] à 'owNcaI'
178
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
179
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Manipulating Sequences
180
FooterLicensed to Kevin Romanteau. Email address: [email protected]
àmutable sequences can be modified
à replace elements
à delete elements
à add elements
à often appended (to the end)
à can also specify where in the sequence to insert
181
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Replacing Single Elements
l[1] = 'hello'
182
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Replacing an entire Slice
my_list = [1, 2, 3, 4, 5]
à Python uses the elements of the sequence in RHS when assigning to a slice
(but not when assigning using a single index)
183
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Deleting Elements
à can delete an element by index
my_list = [1, 2, 3, 4, 5]
del my_list[1]
my_list à [1, 3, 4, 5]
del my_list[1:3]
my_list à [1, 4, 5]
184
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Appending Elements
185
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Inserting an Element
à instead of appending, we can insert at some index
à use sparingly – this is much slower than appending or extending
my_list = [2, 3, 4, 5]
my_list.insert(0, 100)
my_list à [100, 2, 3, 4, 5]
my_list = [2, 3, 4, 5]
my_list.insert(2, 100)
my_list à [2, 3, 100, 4, 5]
à element is inserted so its position is the index - remaining elements are shifted right
186
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
187
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Copying Sequences
188
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Shallow vs Deep Copies
à two types of copies
à shallow copies
à new sequence is created (not same sequence object as original)
à elements in new sequence reference the same elements as original
à deep copies
à new sequence is created (not same sequence object as original)
189
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Shallow Copy
obj 1
index 0 index 0
index 1 obj 2 index 1
index 2 index 2
obj 3
original shallow_copy
190
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Shallow Copy
obj 1
index 0 index 0
index 1 obj 2 index 1
index 2 index 2
obj 3
original shallow_copy
à add/remove/replace element in one does not affect the other
obj 1 index 0
index 0
index 1 obj 2 index 1
index 2 index 2
obj 3 index 3
original obj 4
shallow_copy
191
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Shallow Copy
à but mutating an element will affect both (since it is a shared reference)
obj 1
index 0 index 0
index 1 obj 2 index 1
index 2 index 2
obj 3
original
(modified)
shallow_copy
192
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Creating Shallow Copies
my_list = [1, 2, 3]
my_copy = my_list[:]
my_copy à [1, 2, 3]
my_copy = my_list.copy()
193
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Mutable Elements
my_copy = my_list.copy()
à my_list[0] and my_copy[0] are both referencing the same list ['a', 'b']
194
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Creating Deep Copies
my_copy[0].append('c')
my_copy[0] à ['a', 'b', 'c']
my_list[0] à ['a', 'b']
195
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
196
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Unpacking Sequences
197
FooterLicensed to Kevin Romanteau. Email address: [email protected]
consider a sequence
data = (1, 2, 3) à this is a tuple with three elements
a, b, c = (1, 2, 3)
Since tuples don't actually need the parentheses in this case, we can write:
a, b, c = 1, 2, 3
198
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à this works with any sequence in general
a, b = [10, 20] a à 10
b à 20
a, b, c = 'XYZ' a à 'X'
b à 'Y'
c à 'Z'
199
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à beware!
à number of elements in sequence on RHS must match number of symbols on LHS
a, b = 1, 2, 3
à ValueError (too many values to unpack)
a, b, c = 1, 2
à ValueError (not enough values to unpack)
200
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Swapping Two Variable Values
à this is a common problem
given two variables a and b, swap the value of a and b
Initial State: a à 10 End State: a à 20
b à 20 b à 10
temp = a
a = b
b = temp
201
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Swapping Two Variable Values
à can use unpacking to our advantage
à remember: in an assignment, the RHS expression is evaluated completely first
à then the assignment takes places
a, b = b, a
202
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
203
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Strings
6 204
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à strings are sequence types
205
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Unicode
206
FooterLicensed to Kevin Romanteau. Email address: [email protected]
In the beginning…
… there was ASCII (American Standard Code for Information Interchange)
à addressed the problem of a standard for assigning
208
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à attempts were made to extend the ASCII set
209
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Code Points
à backward compatible with ASCII
ASCII character code for A à 65 (decimal), 41 (hexadecimal)
Unicode code point for A à 65 (decimal), 41 (hexadecimal)
decimal à base 10 (0 – 9)
hexadecimal à base 16 (0-9, A-F)
210
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What is hex anyway?
Decimal system – uses powers of 10 à 10 digits, 0-9
103 102 101 100
9034 = 4 ×10- + 3 ×10. + 0 ×10/ + 9 ×100
9 0 3 4
23 22 21 20
(1011)/ = 1×2- + 1×2. + 0×2/ + 1×20 = 11.-
1 0 1 1
212
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à ord() function
à returns code point for a single character (in decimal)
ord('A') à 65
à hex()
à converts decimal to hex string
hex(65) à '0x41' (0x prefix indicates the number after that is in hex)
213
FooterLicensed to Kevin Romanteau. Email address: [email protected]
https://www.compart.com/en/unicode/U+03B1
hex(ord("α")) à '0x3b1'
214
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Other ways to specify the character in a string
à use escape codes
à by hex code à by name
"The letter \N{Greek Small Letter Alpha} is the first letter of the Greek alphabet."
215
FooterLicensed to Kevin Romanteau. Email address: [email protected]
https://www.compart.com/en/unicode/U+1F40D
217
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Common String Methods
218
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à Python has a ton of string methods
https://docs.python.org/3/library/stdtypes.html#string-methods
220
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Case Folding
s1 = 'hello'
s2 = 'HeLlo'
221
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Stripping
sometimes we want to remove leading and trailing characters
à trailing commas
à whitespace around a string
223
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Splitting Strings
à useful for parsing data from a text file
data = '100, 200, 300, 400' ß a string containing comma
delimited values
à can easily split this on the comma
data.split(',')
à returns a list of strings ['100', ' 200', ' 300', ' 400']
224
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Joining Strings
à this is the opposite of splitting strings
suppose we want to join these strings with `, ` characters between each:
'a' 'b' 'c' 'd'
we could write:
'a' + ', ' + 'b' + ', ' + 'c' + ', ' + 'd'
à "hardcoded"
225
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Joining Strings
'='.join('python') à 'p=y=t=h=o=n'
226
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Finding Substrings
à tests containment
à but gives no indication of where the substring is
227
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à slight variation
à does the string start (or end) with the specified characters
à still a containment test
.startswith('…') .endswith('…')
'python'.startswith('py') à True
'python'.startswith('hon') à False
'python'.endswith('py') à False
'python'.endswith('hon') à True
228
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Finding the Index of a Substring
à used when we need to know the index of the start position of a substring
data.index('correct') à 24
229
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Finding the Index of a Substring
à what if we don't want an exception?
à find à returns -1 if substring is not found
data.find('correct') à 24
data.find('DOW') à -1
230
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Important Note
à use in
à only use index or find when you need to know the index
à in is much faster!
231
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
232
FooterLicensed to Kevin Romanteau. Email address: [email protected]
String Interpolation
233
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à often we want to build strings that contain values from some variable
234
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
We want to build a string that looks like this for display purposes:
à using concatenation:
'open: ' + str(open_) + ', high: ' + str(high) + ', low: ' + str(low) + ', close:' + str(close)
à tedious and error prone! à in fact there is an error, can you spot it?!
235
FooterLicensed to Kevin Romanteau. Email address: [email protected]
String Interpolation
à multiple variants à two most common techniques
'open: {}, high: {}, low: {}, close: {}'.format(open_, high, low, close)
value = 3.14
f'pi is approximately {value}' à 'pi is approximately 3.14'
238
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
239
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Iteration
7 240
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à fundamental aspect of writing programs is repetition
à want to repeat the same process (code) multiple times
deterministic iteration
à we iterate over the elements of some container
à e.g. sequences
à more generally over objects that are iterable
à not all iterables are sequences
àa bag of marbles is iterable, but it is not a sequence!
à for loop
non-deterministic iteration
à we iterate while some condition is True
à while loop
242
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The range Function
243
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The range Object
244
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The range() Function
print(tuple(r)) à (0, 1, 2, 3, 4)
print(list(r)) à [0, 1, 2, 3, 4]
246
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iteration
à we can use a for loop to iterate over the elements of this iterable
(next lecture)
247
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
248
FooterLicensed to Kevin Romanteau. Email address: [email protected]
for Loops
249
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à for loops are used to iterate over elements of any iterable
à the loop mechanism retrieves elements from the iterable one at a time
à the body of the for loop is executed for each element retrieved
à the loop terminates when all elements have been iterated
250
FooterLicensed to Kevin Romanteau. Email address: [email protected]
for x in ['a', 'b']:
y = x + x
note how the body is indented
print(y)
print('done') à just like if…else… code blocks
unindented à not in loop body
1st iteration:
'a' is retrieved and assigned to the symbol x
y is the concatenation of x and x à 'aa'
'aa' is printed to the console
2nd iteration:
'b' is retrieved and assigned to the symbol x
y is the concatenation of x and x à 'bb'
'bb' is printed to the console
3rd iteration: à no more elements à loop terminates
à code after loop executes
à 'done'
251
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iterating over range Objects
à range objects are iterable
output: 0
1
4
9
252
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Loop Bodies (Blocks)
à block can contain any valid Python code
à if…else…
à another loop (nested loop)
for i in range(1, 4):
for j in range(1, i+1): i = 1
print(i, j, i*j) j in range(1, 1+1)
print('')
1 1 1
i = 2
2 1 2 j in range(1, 2+1)
2 2 4
i = 3
3 1 3 j in range(1, 3+1)
3 2 6
3 3 9
253
FooterLicensed to Kevin Romanteau. Email address: [email protected]
data = [10, 20, 30, -10, 40, -5]
à we can iterate over the data and test for negative numbers:
à but we can do one better à we can unpack in the for clause itself
256
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
257
FooterLicensed to Kevin Romanteau. Email address: [email protected]
while Loops
258
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à different than for
à here we want to repeat some code as long as some condition is True
à non-deterministic à we don't necessarily know when condition becomes True
à maybe never! à infinite loop
while expr:
<code block>
output: 10
11
12
13
14
260
FooterLicensed to Kevin Romanteau. Email address: [email protected]
value = 100
output: no output
261
FooterLicensed to Kevin Romanteau. Email address: [email protected]
value = 10
output: 10
9
8
7
6
… infinite loop!!
262
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
263
FooterLicensed to Kevin Romanteau. Email address: [email protected]
continue, break, else
264
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Skipping an Iteration
à sometimes we want to skip an iteration, but without terminating the loop
à continue
à immediately jumps to the next iteration
for i in my_list: 1
if i > 50: 2
continue 3 à when i is 100
print(i) 4
à continue is executed
print('done') 5
'done' à loop jumps to next iteration
265
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à continue is not used too often
à can sometimes make code difficult to read/understand
for i in my_list:
if i > 50:
continue
print(i)
print('done')
266
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Early Termination
à loops can be exited early (before all elements have been iterated)
à break
for i in my_list: 1
if i > 50: 2
break 3
print(i) 'done'
print('done')
à when i is 100
à break is executed
à loop is terminated immediately
267
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Early Termination
268
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
We are scanning through an iterable,
looking for an element equal to
'Python'
If we find the value, we want to found = False
terminate our scan immediately, and
print 'found', otherwise we want for el in my_list:
to print 'not found' if el == 'Python':
found = True
print('found')
break
if not found:
print('not found')
269
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The else Clause
à Python is really confusing here…
à the else clause of a for loop executes if and only if no break was encountered
in my mind I read it as "else if no break"
for i in range(5):
<code block 1>
else: # if no break
<code block 2>
à <code block 2> executes if loop terminated normally
(i.e. no break encountered)
270
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Back to our Example
found = False
for el in my_list:
if el == 'Python':
found = True
print('found') equivalently:
break for el in my_list:
if el == 'Python':
if not found: print('found')
print('not found') break
else: # if no break
print('not found')
271
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
272
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Dictionaries
8 273
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dictionaries are one of the most important data structures in Python
274
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à associating two things together is extremely useful
a phone book à associates a number to a name
DNS à associates a URL with a numeric IP address
book index à associates a chunk of text with a page number
275
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Associative Arrays and Dictionaries
276
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Associating Things
à ASCII table à associates a numeric value to certain characters
A à 65 a à 97 space à 32
B à 66 b à 98 < à 60
… … @ à 64
Z à 90 z à 122 …
279
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Python Dictionaries
à a dictionary is a data structure that associates a value to a key
à both value and key are Python objects
à key must be hashable type (e.g. str, int, bool, float, …) and unique
à value can be any type
à type is dict
à it is a collection of key: value pairs
à it is iterable
à but it is not a sequence type
à values are looked up by key, not by index
à technically there is no ordering in a dictionary
(we'll come back to this point!)
à it is a mutable collection
280
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dictionary Literals
à dictionaries can be created using literals
d = {'a': 97, 'b': 98, 'A': 65, 'B': 66, 'z': 122, 'Z': 90}
à we can use a single line, but often we structure it over multiple lines to
make it more readable
à readability matters!
d = {
'a': 97,
'b': 98,
'A': 65,
'B': 66,
'z': 122,
'Z': 90
}
281
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Looking up values in a Dictionary
d = {
'a': 97,
'b': 98, d['a'] à 97
'A': 65,
d['Z'] à 90
'B': 66,
'z': 122,
'Z': 90
}
282
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Replacing the Value of an existing Key
d = {
'symbol': 'AAPL',
'date': '2020-03-10',
'close': 285
}
d['close'] = 285.34
d = {
'symbol': 'AAPL',
'date': '2020-03-10',
'close': 285.34,
'open': 277.14
} d = {
'symbol': 'AAPL',
del d['open'] à
'date': '2020-03-10',
'close': 285.34}
285
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Common Exceptions
287
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iterating Dictionaries
288
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dictionaries are Iterable
a
for k in data:
à b
print(k)
c
289
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iterating over values
1
for v in data.values():
à 2
print(v)
3
290
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iterating over key:value Pairs
à dictionaries have a method called items()
à items() returns an iterable containing the keys and values in a tuple
à remember unpacking?
a = 1
for k, v in data.items()
à b = 2
print(f'{k} = {v}')
c = 3
291
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The keys() Method
Technically there is also a keys() method
a
for k in data.keys():
à b
print(k)
c
292
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Insertion Order
à we saw in sequence types that elements have positional order
à not every iterable has positional order
à we can pull marbles out of a bag, but there is no particular order
293
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Insertion Order
what does insertion order mean?
à literal: insertion order is the order in which the key:value pairs are listed out
294
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
295
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Working With Dictionaries
296
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Membership Testing
à can test if a key exists in a dictionary using in
d = {'a': 1, 'b': 2}
'a' in d à True
'x' in d à False
297
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Useful Methods and Functions
298
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Other Methods to Create Dictionaries
d = {'a': 1, 'b': 2}
d = dict(a = 1, b = 2)
à symbols must be valid variable names and will be used, in string
form, as the keys
à can create a dictionary with several keys all initialized to the same value
d = dict.fromkeys(['cnt_1', 'cnt_2', 'cnt_3'], 0)
d à {'cnt_1': 0, 'cnt_2': 0, 'cnt_3': 0}
300
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The get() Method
à trying to retrieve a non-existent key results in a KeyError exception
d.get('length', 0) à 10
the key exists, so the corresponding value (10) is returned
d.get('height', 0) à 0
the key does not exist, so the default (0) is returned
d.get('height') à None
the key does not exist, so the default default-value (None) is returned
302
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The get() Method
à using get() allows us to simplify our code to assign a default for missing keys
if 'ssn' in person_dict:
social = person_dict['ssn']
else:
social = ''
303
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Merging one Dictionary into Another
à the update() method
à takes a single argument: another dictionary
d1.update(d2)
the key:value pairs of d2 will be merged into d1
304
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Merging one Dictionary into Another
d1 = {'a': 1, 'b': 2}
305
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
306
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Sets
9 307
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What are Python sets?
à just like a mathematical set
à a collection of elements
à no ordering to the elements
à each element is unique
à it is an iterable
à but no guarantee on what the iteration order will be
à intersection
à difference
309
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Python Sets
310
FooterLicensed to Kevin Romanteau. Email address: [email protected]
think back to keys in a dictionary
313
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Defining Sets
à can also make a set from any iterable (of hashable elements)
l = [1, 2, 3, 4, 5]
s = set(l) s à {1, 2, 3, 4, 5}
l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
s = set(l) s à {1, 2, 3, 4, 5}
314
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à use a for loop for iteration
315
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
316
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Common Set Operations
317
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Disjointedness
s1.isdisjoint(s2)
à True if no common elements exist
à False if one or more common elements exist
318
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Adding and Removing Elements
s.remove(100) à KeyError
319
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Subsets and Supersets
s1 < s2 à True if s1 is a strict subset of s2
s1 <= s2 à True if s1 is a subset of s2
s1 > s2 à True if s1 is a strict superset of s2
s1 >= s2 à True if s1 is a superset of s2
320
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Unions and Intersections
s1 | s2 à returns the union of s1 and s2
𝑠. 𝑠/
s1 | s2 à {1, 2, 3, 4, 5}
321
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Set Difference
the difference s1 – s2 of two sets is
all the elements of one set minus the 𝑠. 𝑠/
elements of the other set
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 - s2 à {1, 2}
s2 - s1 à {4, 5}
322
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à always keep sets in mind when coding
323
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
324
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Comprehensions
10 325
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à comprehensions are an easy way to create new iterables from other iterables
Example
given a list of 2D vectors
[(0, 0), (1, 1), (1, 2), (3, 5)]
create a new list containing the magnitude of each vector
à [02 + 02, 12 + 12, 12 + 22, 32 + 52]
à [0, 2, 5, 34]
326
FooterLicensed to Kevin Romanteau. Email address: [email protected]
List Comprehensions
327
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à a comprehension is a way to use one iterable to create another
328
FooterLicensed to Kevin Romanteau. Email address: [email protected]
List Comprehensions
a list comprehensions is used to generate a list object
Example
329
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à can do this without comprehensions
330
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à or we can use a comprehension
numbers = (1, 2, 3, 4, 5)
331
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à comprehensions offer a more concise (and more efficient!) way of
creating one iterable from another
sq = []
for number in numbers:
sq.append(number ** 2)
332
FooterLicensed to Kevin Romanteau. Email address: [email protected]
what about something like this?
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
333
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à can use a "standard" approach
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
à in general
335
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dictionary/Set Comprehensions
336
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à similar to list comprehensions
à use {} instead of []
337
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Dictionary Comprehension
338
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
Given two lists one of which contains widget names, the other containing
the sales number for each of those widgets – ordered the same
widgets = ['widget 1', 'widget 2', 'widget 3', 'widget 4']
sales = [10, 5, 15, 0]
à create a dictionary whose keys are the widget names, and the value
the number of sales, but only include widgets that had sales.
à "traditional" approach
d = {}
for i in range(len(widgets)):
if sales[i] > 0:
d[widgets[i]] = sales[i]
339
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
341
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
Given a list of integers, create a set that contains a unique collection of the
squares of just the even integers
numbers = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
s = {number ** 2
for number in numbers
if number % 2 == 0
}
342
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
343
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Exceptions
11 344
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What are exceptions?
à exceptions are special events that happen when something out of the
ordinary happens while our code is running
345
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Terminology
346
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Exception Hierarchy
à Python exceptions form a hierarchy
(we'll cover what that means precisely when we look at
Object Oriented Programming - OOP)
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
à exception handling
351
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Why EAFP?
Something that is exceptional should be infrequent
à out of every 1,000 times we run, we expect division by zero to occur 5 times
LBYL à test that divisor is non-zero 1,000 times
EAFP à just do it, and handle the division by zero error 5 times
à often more efficient
352
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Exception Handling Flow
à an exception occurs
à an exception object is created
à an exception flow is started
à we do nothing about it
à program terminates
354
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à often we want to start an exception flow ourselves
355
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
356
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à raising an exception ourselves results in the same exception flow that
Python does when it raises some exception
357
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
358
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Handling Exceptions
359
FooterLicensed to Kevin Romanteau. Email address: [email protected]
General Suggestions for Exception Handling
à in general we do not want to just handle any exception anywhere in our code
à too much work
à cannot anticipate every point of failure
à it's OK for program to terminate - we can figure out what went
wrong and attempt to fix it later – possibly handling that case
specifically
à if we don't know exactly why or where the problem occurs in our
code, there's not much we can do to recover from the exception
360
FooterLicensed to Kevin Romanteau. Email address: [email protected]
try…except…
à wrap the code we want to implement an exception handler for
inside a try block
à we handle possible exception(s), using except blocks (one or more)
361
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Handling and re-raising an exception
raise à re-raises the same exception that caused the except block to be entered
362
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Application
à one very common case for re-raising exceptions is for error logging
à we can view the logs after our program has terminated abnormally
try:
…
except Exception as ex:
log(ex)
raise
363
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à what do I mean "something else handles it"?
à we'll see this more when we cover functions
364
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Handling Multiple Exception Types
à not limited to a single except block
try:
…
except IndexError as ex:
…
except ValueError as ex:
…
except Exception as ex:
…
à Python will match the exception to the first type that matches in
sequence of except blocks
à so write except blocks from most specific to least specific exception types
à remember that exception hierarchy we looked at!
365
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The finally Clause
try:
…
except ValueError as ex:
…
except IndexError as ex:
…
finally:
# always runs no matter what, before exception flow resumes
366
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Application
à useful when we want a piece of code to always run
à whether an exception has occurred or not
à whether the exception was handled or not
à whether exception was re-raised or a new one raised
try:
open_database_connection()
start_transaction()
write_data()
commit_transaction()
except WriteException as ex:
rollback_transaction()
raise
finally:
close_database_connection()
367
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
368
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
12 369
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à an iterable is something that can be iterated over
à i.e. we can take one element, then the next, then the next, until
we've covered all elements
à no specific iteration order is mandated
370
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à so we have two concepts here
371
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Iterables and Iterators
372
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à an iterable is something that can be iterated over
à keep track of what it's given us so far (so it does not give us the same
element twice)
373
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à an iterable is just a collection of objects
à it doesn't know anything about how to iterate
à however it knows how to create and give us an iterator when we need it
à the iterator has a special method called __next__() that can be called
to get the next element
à can also use the next() function
l = [1, 2, 3, 4, 5]
iterator = iter(l)
try:
while True:
# return next(iterator) – here we'll just print it
print(next(iterator))
except StopIteration:
# expected when we reach the end
# so silence this exception
pass
375
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à the key thing here is that we can see the iterator has some state
à it has a __next__() method
à but there's no going back, or starting from the beginning again
à to do that we have to request a new iterator
à and that's what a for loop does – it requests a new iterator from the iterable
before it starts looping
à objects such as lists, tuples, string, dictionaries, sets, range objects are iterables
à but some objects in Python are iterators – not iterables
à iterators actually implement an __iter__ method
à but they just return themselves (with their current state), not a new iterator
à they allows us to iterate over them
à but only once
376
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
377
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Generators
378
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à we've seen list, dictionary and set comprehensions
result = []
for i in range(5):
result.append(i ** 2)
à no tuple comprehension
379
FooterLicensed to Kevin Romanteau. Email address: [email protected]
so what does this (valid) expression do?
(i ** 2 for i in range(5))
380
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Why use generators?
à memory efficiency
à e.g. take all the rows from a file, and write them out, transformed
to some other file
à read the entire file in memory, iterate through that and save rows
à entire file in memory!
à you may not have enough memory!
381
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Why use generators?
à performance (possibly)
à if you only need to read the first few elements of the iterable
382
FooterLicensed to Kevin Romanteau. Email address: [email protected]
What's the downside of generators?
à generators are lazy iterators
à one-time use
à not good if you need to iterate through the same iterable many times
383
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Creating Generators
384
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
385
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Functions
13 386
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à we have used functions a lot so far
print()
iter()
next()
list()
math.sqrt()
387
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Why?
à problem decomposition
388
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à when we create a function, we may also want values to be passed into
it when it is called
à arguments or parameters
390
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Callables
à an object is callable if it can be called – using ()
391
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Custom Functions
392
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à functions can be defined using the def keyword
393
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
def say_hello():
print('Hello!')
say_hello() à Hello!
say_hello() à Hello!
but no return?
394
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Example
def one():
return 1 function returns the value 1 when it is called
395
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à usually functions contain a little more complex code
def current_time_utc():
return datetime.utcnow().isoformat()
result = current_time_utc()
result à "2020-03-31T02:44:38.490923"
396
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à functions are usually more helpful when we can pass values to them
len(my_iter)
à every time we call the len function we can pass a different value
à the function body (implementation) of the len function starts running
397
FooterLicensed to Kevin Romanteau. Email address: [email protected]
def subtract(a, b):
return a - b
subtract(10, 7) à 3
à positional arguments
398
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Namespaces
à when a function is called
à it knows nothing about how it was called before
399
FooterLicensed to Kevin Romanteau. Email address: [email protected]
abs_max(1, -2)
def abs_max(a, b): {'a': 1, 'b': -2}
abs_a = abs(a) {'a': 1, 'b': -2, 'abs_a': 1}
abs_b = abs(b) {'a': 1, 'b': -2, 'abs_a': 1, 'abs_b': 2}
if abs_a > abs_b:
max_val = abs_a
else:
{'a': 1, 'b': -2, 'abs_a': 1, 'abs_b': 2,
max_val = abs_b 'max_val': 2}
return max_val
400
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
401
FooterLicensed to Kevin Romanteau. Email address: [email protected]
* Arguments
402
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à saw how to specify positional parameters in a function
average(1)
average(1, 2, 3)
average(1, 2, 3, 4)
403
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à could write a function to use an iterable as a single argument
def average(iterable):
return sum(iterable) / len(iterable)
average([1, 2, 3])
average([1])
404
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à Python supports a special parameter type for this
def average(*values):
# return average
à this means we can call average with any number of arguments
average(1)
average(1, 2, 3, 4, 5)
405
FooterLicensed to Kevin Romanteau. Email address: [email protected]
def average(*values):
print(type(values))
print(values)
def average(*values):
return sum(values) / len(values)
406
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à often you will see code that uses *args
407
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
408
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Default Values
409
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à possible to specify optional parameters
à it needs a value
à we can specify a default value to use if the argument is not supplied
410
FooterLicensed to Kevin Romanteau. Email address: [email protected]
def func(a=1):
print(a)
a default value to use if a is not supplied
when function is called
func() à 1
func(10) à 10
à all positional parameters after that must specify a default value too
411
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à how would you interpret this?
func(10)
à don't know!
412
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à so once we have default arguments we need to specify default for all
parameters after it
413
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
414
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Keyword-Only Arguments
415
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à we saw how positional parameters can be passed
à positionally
à as a named argument à also called a keyword argument
func(1, 2, 3)
416
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à can also make passing an argument by name mandatory
def func(a, b, c)
417
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à one way is to use a * parameter
418
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à but this allows someone to pass in as many positional arguments as they want
à we still have to tell Python that there are no more positional arguments
419
FooterLicensed to Kevin Romanteau. Email address: [email protected]
def func(a, b, *, c):
…
à so c is a keyword-only argument
420
FooterLicensed to Kevin Romanteau. Email address: [email protected]
def func(a, b, *, c):
…
421
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Default Values
à can mix default values for both positional and keyword-only arguments
422
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Arbitrary Number of Keyword-only Parameters
423
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à ** keyword-only arguments are scooped up into a dictionary
à key is the argument name
à value is the argument value
a à 10
func(10, d=2, x=10, y=20) d à 2
func(a=10, d=2, x=10, y=20) others à {
'x': 10,
func(x=10, y=20, d=2, a=10) 'y': 20
}
424
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
425
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Lambda Functions
426
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à lambda functions are just functions
427
FooterLicensed to Kevin Romanteau. Email address: [email protected]
lambda a, b: a + b
f = lambda a, b: a + b
f(10, 20) à 30
428
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à can always use a function defined using def instead of these lambdas
429
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
430
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Intro to Python for Financial Services
Some Built-In
Functions
14 431
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à in this section we are going to look at some more of Python's built-in functions
à https://docs.python.org/3/library/functions.html
à and that does not even include the thousands of functions available
in Python's standard library
433
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à round() is a built-in function that can be used to round floats
2.5 à 2
434
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à use round() to round to an integer
round(1.8) à2
round(-1.8) à -2
round(1.5) à2
round(2.5) à2
435
FooterLicensed to Kevin Romanteau. Email address: [email protected]
1
à can also use round() to round to closest multiple of
10
round(value, exponent)
1
exponent is used to specify what power of to round to
10
à let's look at it mathematically first (i.e. without worrying about float representations)
437
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Rounding Ties in Floats
à technically rounds to closest number that ends with an even digit
round(0.125, 2) à 0.12
à so why this?
round(0.325, 2) à 0.33 why not 0.32?
0.325 à 0.325000000000000011102230246252
438
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
439
FooterLicensed to Kevin Romanteau. Email address: [email protected]
sorted, min and max
440
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sorting Numbers
à numbers have a natural sort order
à they can be sorted ascending or descending by that sort order
à sorted is a built-in function that can be used to sort a collection of numbers
à single positional argument: an iterable containing the numbers
à by default, it sorts in ascending order
441
FooterLicensed to Kevin Romanteau. Email address: [email protected]
t = (1, 10, 2, 9, 3, 8)
sorted(t)
à [1, 2, 3, 8, 9, 10]
sorted(t, reverse=True)
à [10, 9, 8, 3, 2, 1]
442
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sorting Strings
Numbers have a natural sort order
A à 65 Z à 90
à'A' < 'Z' < 'a' < 'z'
a à 97 z à 122
443
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à so Python will use "alphabetical" sorting, but upper case letters will be
sorted before their equivalent lower case versions
sorted(['Boy', 'baby'])
444
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Sorting Other Types
à list of Persons
à by name
à by age
à by profession
445
FooterLicensed to Kevin Romanteau. Email address: [email protected]
min and max
à closely related to sorting
(or you could sort in the other direction in both cases and pick the last element)
446
FooterLicensed to Kevin Romanteau. Email address: [email protected]
min([1, 10, 2, 9, 8]) à 1
min([], default=0) à 0
447
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à can also use an arbitrary number of positional arguments instead
min(1, 10, 2, 9, 3, 8) à 1
max(1, 10, 2, 9, 3, 8) à 10
à we'll come back to min and max when we look at sorting again later in
this course
448
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
449
FooterLicensed to Kevin Romanteau. Email address: [email protected]
The zip() Function
450
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à the zip() function is a very useful and often used function
451
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à could do this:
combo = [(l1[i], l2[i]) for i in range(len(l1))]
but, we may have an issue if the two lists are not of the same length
àhave to stop at the shortest of the two lengths
452
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à that's what the zip() function does!
list(combo) à []
453
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à if you want to iterate multiple times over the same zipped collection
à iterating over zip() result, just iterates over the iterables simultaneously
454
FooterLicensed to Kevin Romanteau. Email address: [email protected]
à zip is extensible
l1 = [1, 2, 3]
l2 = [1, 2, 3, 4, 5]
l3 = [1, 2, 3, 4, 5, 6, 7]
455
FooterLicensed to Kevin Romanteau. Email address: [email protected]
Coding
456
FooterLicensed to Kevin Romanteau. Email address: [email protected]