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

Lecture02 Slides

The document discusses Python data structures including lists, tuples, ranges, and sets. It provides examples of how to create and manipulate each type of data structure, focusing on lists and how they can be indexed, sliced, and modified. It also covers the differences between mutable and immutable data types in Python.

Uploaded by

tonggennn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lecture02 Slides

The document discusses Python data structures including lists, tuples, ranges, and sets. It provides examples of how to create and manipulate each type of data structure, focusing on lists and how they can be indexed, sliced, and modified. It also covers the differences between mutable and immutable data types in Python.

Uploaded by

tonggennn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

27/09/2023, 12:14 Lecture02 slides

Attendance
Register at: http://go.qub.ac.uk/finattend4

Campus Code: XXXX


27/09/2023, 12:14 Lecture02 slides

Python Basics
Content Outline
Data Structures
Functions
Developer Practices
27/09/2023, 12:14 Lecture02 slides

Data structures
Container variables are structures that can hold multiple values or
collections of values
Sequence type containers are like arrays
list , tuple , range
their elements can be enumerated/indexed
this allows their values to be accessed by their position
Unordered types include:
set which behaves like a mathematical set (no duplicates
allowed)
dict which contains key/value pairs with element values
accessed by their key
27/09/2023, 12:14 Lecture02 slides

Lists
A list is an ordered array
Stores mixed data types (e.g. integers and strings in the same list)
Allow duplicates
Created using square brackets [] and accessed via square brackets
[]
Mutable - values can be modifed after creation
Can be used to replicate stacks (LIFO) and queues (FIFO)
Have various methods to help manipulate them (e.g. insert ,
append )
27/09/2023, 12:14 Lecture02 slides

In [1]: #List examples


list1 = []
list2 = list()
list3 = [2, 3, 5, 7, 11]
list4 = ["finance", "economics", "accounting"]
list5 = [list3, list4]
list6 = [5, 'e']

print(list5)

[[2, 3, 5, 7, 11], ['finance', 'economics', 'accounting']]


27/09/2023, 12:14 Lecture02 slides

Empty lists

If you know in advance that you need to store n values, create a list of
the appropriate size with null values
Can use the keyword None for this
More efficient than extending a list one element at a time
In [2]: #Create a list of size 10, without populating any values
A = [None] * 10
print(A)

[None, None, None, None, None, None, None, None, None, None]
27/09/2023, 12:14 Lecture02 slides

Python is zero based


An array with 10 elements is indexed from 0, 1, 2, ... 9
In [3]: print("I will not forget that Python is zero-based!\n" * 10)

I will not forget that Python is zero-based!


I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
I will not forget that Python is zero-based!
27/09/2023, 12:14 Lecture02 slides
27/09/2023, 12:14 Lecture02 slides

In [4]: #Create list


A = [2, 3, 5, 7, 11]

#Find length of A (using a f string here)


print(f"A has {len(A)} elements")

#Access 3rd element - count from zero!


print("3rd element is", A[2])

#update first value


A[0] = 1
print("After modifying first element", A)

A has 5 elements
3rd element is 5
After modifying first element [1, 3, 5, 7, 11]
27/09/2023, 12:14 Lecture02 slides

Tuple
A tuple is an ordered array
Stores mixed data types
Allow duplicates
Created using round brackets () but accessed via square brackets
[]
Immutable - values cannot be modifed after creation
27/09/2023, 12:14 Lecture02 slides

In [5]: #Tuple examples


tuple1 = ()
tuple2 = tuple()
tuple3 = (2, 3, 5, 7, 11)
tuple4 = ("finance", "economics", "accounting")
tuple5 = (tuple3, tuple4)
tuple6 = (5, 'e')
27/09/2023, 12:14 Lecture02 slides

In [6]: #Access 3rd element - count from zero!


print("3rd element is", tuple3[2])

#This won't work – it's a tuple!


try:
tuple3[0] = 1
except:
print("something went wrong!")

3rd element is 5
something went wrong!
27/09/2023, 12:14 Lecture02 slides

Range
A range contains integer sequences
Created using function range(start, stop, step)
start defaults to 0
step defaults to 1
includes start but excludes stop
Immutable - values cannot be modifed after creation
Ideal for iteration ( for loops)
27/09/2023, 12:14 Lecture02 slides

In [7]: #Sequence of integers 0 to 9


r1 = range(10)

#Sequence of integers 1 to 10
r2 = range(1,11)

#Convert to list
a = list(r1)

#Sequence of integers 10 to 1
r3 = range(10,0,-1)

#Print - the * symbol unpacks the range


print(*r3)

10 9 8 7 6 5 4 3 2 1
27/09/2023, 12:14 Lecture02 slides

Working with arrays

a:b:c notation mirrors the range function


Known as slicing (there is also a slice function)
Used to extract a subsequence from arrays
values a up to (but not including) b advancing in steps of c
if c is omitted its value is defaulted to 1
if a is omitted its value is defaulted to 0
if b is omitted its value is defaulted to the length of the array
being accessed
negative step values indicate counting backwards from the end
of the array
default logic reverses ( a starts at the end)
27/09/2023, 12:14 Lecture02 slides

In [8]: A = list(range(10))

#Remember its zero based!


print("Values from position 2 through 3:", A[2:4])

print("Values from positions 3, 5, 7 & 9:", A[3:10:2])

print("First three values:", A[:3])

print("Fourth value onwards:", A[3:])

print("All but last three values:", A[:-3])

Values from position 2 through 3: [2, 3]


Values from positions 3, 5, 7 & 9: [3, 5, 7, 9]
First three values: [0, 1, 2]
Fourth value onwards: [3, 4, 5, 6, 7, 8, 9]
All but last three values: [0, 1, 2, 3, 4, 5, 6]
27/09/2023, 12:14 Lecture02 slides

In [9]: A = list(range(10))

#Working backwards (negative step)


#Default logic start/stop reverses
print("count down from 9 >", *A[::-1])

print("count down from 5 > ", *A[5::-1])

#Still stops one short


print("count down to 6 > ", *A[:5:-1])

count down from 9 > 9 8 7 6 5 4 3 2 1 0


count down from 5 > 5 4 3 2 1 0
count down to 6 > 9 8 7 6
27/09/2023, 12:14 Lecture02 slides

Sets
A set is unordered and unindexed
Prohibits duplicates
Can be created using curly brackets {} or set()
An immutable version is the frozenset
27/09/2023, 12:14 Lecture02 slides

In [10]: #Create empty set


myset = set()

#create set
myset = {"alpha", "beta", "gamma"}

#add new member


myset.add("eta")
27/09/2023, 12:14 Lecture02 slides

In [11]: #remove member – warning if does not exist


myset.remove("beta")

#remove member – no warning


myset.discard("beta")

print(myset)

#check membership
print("alpha" in myset)

{'alpha', 'eta', 'gamma'}


True
27/09/2023, 12:14 Lecture02 slides

Dictionary
A dict is mutable and indexed
It is ordered (since python v3.6) - keys are stored in insertion order.
Created using curly brackets {} but their elements are not single
values
Each element is key/value pair
Keys must be unique and are typically strings (must be immutable)
They are used to 'look up' their associated values
Values can be any data type (including a structured one)
27/09/2023, 12:14 Lecture02 slides

In [12]: #Create dict


mydict = {"red": 1, "amber": 2, "green": 3}

#Find value associated with key


print("value corresponding to amber:", mydict["amber"])

#Check key exists


print("is amber a key in the dict?", "amber" in mydict)

#Update or add a new value in dictionary


mydict["stop"] = 0
print("value corresponding to stop:", mydict["stop"])

value corresponding to amber: 2


is amber a key in the dict? True
value corresponding to stop: 0
27/09/2023, 12:14 Lecture02 slides

The get method of a dictionary can also be used to retrieve values in a


way the specifies a default value should the key not be found in the
dictionary.
27/09/2023, 12:14 Lecture02 slides

In [13]: #When key is not in the dictionary

#This would throw an error (so commented out)


#print("what value is blue?", mydict["blue"])

#This works and returns default -1


print("what value is blue?", mydict.get("blue", -1))

what value is blue? -1


27/09/2023, 12:14 Lecture02 slides

In [14]: #Extract a list of just the dictionary keys


print("Dictionary keys:", mydict.keys())

#Extract a list of just the dictionary values


print("Dictionary values:", mydict.values())

Dictionary keys: dict_keys(['red', 'amber', 'green', 'stop'])


Dictionary values: dict_values([1, 2, 3, 0])
27/09/2023, 12:14 Lecture02 slides

In [15]: #Extract a list of the dictionary key/value pairs (as tuples)


print("Dictionary key/value pairs:", mydict.items())

Dictionary key/value pairs: dict_items([('red', 1), ('amber', 2), ('gr


een', 3), ('stop', 0)])
27/09/2023, 12:14 Lecture02 slides

Coding in Python
A code module can contain statements, functions and classes
where do functions end and statements begin?
Many languages use parenthesis
statements inside brackets are treated as a block of code
Python uses indentation
normally 1 tab stop = 4 spaces
Indentation defines flow control
Changing indentation changes what your code will do!
27/09/2023, 12:14 Lecture02 slides

Functions
Python comes with built-in functions and a range of packages
Functions within packages must be imported before use
Can import entire libraries or single functions
Packages can be structured into sub-packages and modules
How you import something will determine how it can be used (called)
Can assign an alias and reference by a more convenient name
27/09/2023, 12:14 Lecture02 slides

In [16]: #Importing a package


import math

#Find functions within package


print(dir(math))

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'aco


s', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'com
b', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc',
'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isna
n', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log
2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radian
s', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc',
'ulp']
27/09/2023, 12:14 Lecture02 slides

In [17]: #import a single function


from math import exp

print(exp(1))

#Import a package and assign an alias


import numpy as np

#Can now access its methods using alias


a = np.zeros(3)
print(a)

2.718281828459045
[0. 0. 0.]
27/09/2023, 12:14 Lecture02 slides

User defined functions


Defined using keyword def
The body of the function must be indented
Functions may have:
a fixed number of input parameters
a variable number of input parameters
input parameters which may be omitted (optional/defaulted)
Functions may return:
no result
a single result
multiple results (as a tuple)
27/09/2023, 12:14 Lecture02 slides

In [18]: #create a function (i.e. define)


def powerof(a, n):
"""this is a multiline docstring
it provides help for the function, or does it?"""
return a**n

help(powerof)

#call a function - supply inputs in order of function def


powerof(2,3)

Help on function powerof in module __main__:

powerof(a, n)
this is a multiline docstring
it provides help for the function, or does it?

Out[18]:
8
27/09/2023, 12:14 Lecture02 slides

Input parameters

parameters are the names used to define a function's inputs


arguments are the values that are passed to the function when called
The arguments you use to call a function need not match a function's
input parameters
Although often it makes sense to make them the same
Variables created within a function have local scope
They are temporary working variables that will be destroyed after
exiting the function
27/09/2023, 12:14 Lecture02 slides

Flexible input arguments

Input arguments can be specified by position or explicitly by keyword


Positional input parameters come first
In [19]: #Input parameters with a supplied default become optional
#Optional input parameters should be placed at the
#end of the list of inputs

def powerofn(a, n=2):


return a**n

#Function can now be called with fewer inputs


powerofn(4)

Out[19]:
16
27/09/2023, 12:14 Lecture02 slides

In [20]: #Input parameters can be specified by name


#Only supply the input parameters you need to
def describeme(name, subject = 'finance', position = 'student'):
text = "My name is " + name
text = text + "; I am a " + subject + " " + position
return text

describeme('Alan', position='lecturer')

Out[20]:
'My name is Alan; I am a finance lecturer'
27/09/2023, 12:14 Lecture02 slides

Variable number of inputs

Functions can take an arbitrary number of inputs


Accommodated by wrapping up multiple parameters in a tuple
only allowed one such input for a function
place a * before the parameter name
These variadic arguments will normally appear after all other inputs
they 'scoop up' all remaining input arguments passed to the
function
any arguments appearing after this should be keyword-only
See https://docs.python.org/3/tutorial/controlflow.html#arbitrary-
argument-lists
27/09/2023, 12:14 Lecture02 slides

In [21]: def describeme(name, *languages,


subject = 'finance',
position = 'student'):

text = f'My name is {name}; I am a {subject} {position} \n' + \


f'My favouriate languages are {", ".join(languages)}.'
return text

text = describeme('Alan', 'python', 'r', 'C++',


'VBA', position='lecturer')
print(text)

My name is Alan; I am a finance lecturer


My favouriate languages are python, r, C++, VBA.
27/09/2023, 12:14 Lecture02 slides

Variable number of outputs

Functions can return mulitple outputs


But the individual results must be part of a single structure such as a
container or other object
Providing a comma separated list of return values results in a tuple
being returned
The function output can be assigned to a single variable or a comma
separated list
27/09/2023, 12:14 Lecture02 slides

In [22]: def multipleoutputs():


return 'one', 2

#Assign return values to a single variable


t = multipleoutputs()
print("t is a ", type(t),"\n")

#Assign return values to individual variables


a, b = multipleoutputs()
print("a is a ", type(a))
print("b is a ", type(b))

t is a <class 'tuple'>

a is a <class 'str'>
b is a <class 'int'>
27/09/2023, 12:14 Lecture02 slides

Lambda Expressions

Short single-line functions can be created with the lambda keyword


Functions created with lambda rather than def are anonymous
the function itself has no name
it returns a function object that can be assigned to a variable
thereafter this acts like a function
Useful as inputs into higher order functions
e.g. filter (which uses a function to filter a list)
27/09/2023, 12:14 Lecture02 slides

In [23]: #Create simple lambda function


sqme = lambda x : x**2
print("output =",sqme(5),"\n")

#Use a lambda function to perform an operation


A = [1, 2, 3, 4, 5, 6]

B = [sqme(x) for x in A]
print("B =",B)

#extract even numbers


C = list(filter(lambda x: (x%2 == 0) , A))
print("C =",C)

output = 25

B = [1, 4, 9, 16, 25, 36]


C = [2, 4, 6]
27/09/2023, 12:14 Lecture02 slides

Good developer practices


Use white space to aid code readability
Use code comments to document intended functionality and usage
Use meaningful indentifiers
Avoid hard-coding but also avoid unncessary variable creation
Code for the unexpected to prevent possible errors!
Construct comprehensive test plans to validate your work
27/09/2023, 12:14 Lecture02 slides

Appendix
Check list
Can you:
[ ] describe the salient features of a list, tuple, range, set,
dict ?
[ ] create and access the elements of these structures?
[ ] import and call a function from a built-in libary?
[ ] create and call a custom function with:
[ ] optional input parameters?
[ ] multiple input parameters?
[ ] multiple output parameters?
27/09/2023, 12:14 Lecture02 slides

Resources
https://docs.python.org/3/tutorial/datastructures.html
https://docs.python.org/3/reference/import.html
https://www.w3schools.com/python/python_lists.asp
https://www.w3schools.com/python/python_functions.asp
27/09/2023, 12:14 Lecture02 slides

In [24]: #Find built in functions (last 30)


print(dir(__builtins__)[-30:])

['locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct',


'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reverse
d', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticme
thod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

You might also like