OOP and Scripting in Python Advanced Features · Structure of a Python Script I Every Python le...
Transcript of OOP and Scripting in Python Advanced Features · Structure of a Python Script I Every Python le...
OOP and Scripting in PythonAdvanced Features
Giuliano Armano Emanuele Tamponi
Advanced Features
Structure of a Python Script
More on Defining FunctionsDefault Argument ValuesKeyword ArgumentsArbitrary Argument ListsLambda FormsExercises
More on ListsFunctional Programming ToolsList ComprehensionsExercises
Looping TechniquesIteratorsGeneratorsGenerator Expressions
Structure of a Python Script
I Every Python file (extension .py) is called a module
1 #!/usr/bin/python
2
3 # Import other modules
4
5 # Define your function , classes , variables and so on
6
7 if __name__ == ’__main__ ’:
8 print ’Hello , World!’
I To run a Python module from console, python must be inyour path
I If so, you can open a prompt a write:
1 $ python program_name.py
2 Hello , World!
I ... otherwise, try with:
1 $ C:\ Python27\python.exe program_name.py
Structure of a Python Script
I Every Python file (extension .py) is called a module
1 #!/usr/bin/python
2
3 # Import other modules
4
5 # Define your function , classes , variables and so on
6
7 if __name__ == ’__main__ ’:
8 print ’Hello , World!’
I To run a Python module from console, python must be inyour path
I If so, you can open a prompt a write:
1 $ python program_name.py
2 Hello , World!
I ... otherwise, try with:
1 $ C:\ Python27\python.exe program_name.py
Structure of a Python Script
I Every Python file (extension .py) is called a module
1 #!/usr/bin/python
2
3 # Import other modules
4
5 # Define your function , classes , variables and so on
6
7 if __name__ == ’__main__ ’:
8 print ’Hello , World!’
I To run a Python module from console, python must be inyour path
I If so, you can open a prompt a write:
1 $ python program_name.py
2 Hello , World!
I ... otherwise, try with:
1 $ C:\ Python27\python.exe program_name.py
Structure of a Python Script
I Every Python file (extension .py) is called a module
1 #!/usr/bin/python
2
3 # Import other modules
4
5 # Define your function , classes , variables and so on
6
7 if __name__ == ’__main__ ’:
8 print ’Hello , World!’
I To run a Python module from console, python must be inyour path
I If so, you can open a prompt a write:
1 $ python program_name.py
2 Hello , World!
I ... otherwise, try with:
1 $ C:\ Python27\python.exe program_name.py
Default arguments values (1)
1 def ask_ok(prompt ,retries=4,complaint=’Yes or no , please!’):
2 while True:
3 ok = raw_input(prompt)
4 if ok in (’y’, ’ye’, ’yes’):
5 return True
6 if ok in (’n’, ’no’, ’nop’, ’nope’):
7 return False
8 retries = retries - 1
9 if retries < 0:
10 raise IOError(’refusenik user’)
11 print complaint
How can you call this function?
I ask_ok(’Do you really want to quit?’)
I ask_ok(’OK to continue?’, 2)
I ask_ok(’OK to continue?’, 2, ’Only yes or no.’)
Default arguments values (1)
1 def ask_ok(prompt ,retries=4,complaint=’Yes or no , please!’):
2 while True:
3 ok = raw_input(prompt)
4 if ok in (’y’, ’ye’, ’yes’):
5 return True
6 if ok in (’n’, ’no’, ’nop’, ’nope’):
7 return False
8 retries = retries - 1
9 if retries < 0:
10 raise IOError(’refusenik user’)
11 print complaint
How can you call this function?I ask_ok(’Do you really want to quit?’)
I ask_ok(’OK to continue?’, 2)
I ask_ok(’OK to continue?’, 2, ’Only yes or no.’)
Default arguments values (1)
1 def ask_ok(prompt ,retries=4,complaint=’Yes or no , please!’):
2 while True:
3 ok = raw_input(prompt)
4 if ok in (’y’, ’ye’, ’yes’):
5 return True
6 if ok in (’n’, ’no’, ’nop’, ’nope’):
7 return False
8 retries = retries - 1
9 if retries < 0:
10 raise IOError(’refusenik user’)
11 print complaint
How can you call this function?I ask_ok(’Do you really want to quit?’)
I ask_ok(’OK to continue?’, 2)
I ask_ok(’OK to continue?’, 2, ’Only yes or no.’)
Default arguments values (1)
1 def ask_ok(prompt ,retries=4,complaint=’Yes or no , please!’):
2 while True:
3 ok = raw_input(prompt)
4 if ok in (’y’, ’ye’, ’yes’):
5 return True
6 if ok in (’n’, ’no’, ’nop’, ’nope’):
7 return False
8 retries = retries - 1
9 if retries < 0:
10 raise IOError(’refusenik user’)
11 print complaint
How can you call this function?I ask_ok(’Do you really want to quit?’)
I ask_ok(’OK to continue?’, 2)
I ask_ok(’OK to continue?’, 2, ’Only yes or no.’)
Default Argument Values (2)
Default values are evaluated at the point of function definition inthe defining scope.
1 >>> i = 5
2 >>> def f(arg=i):
3 ... print arg
4 >>> i = 6
5 >>> f()
1 5
Important warning: default values are evaluated only once.
1 def f(a, L=[]):
2 L.append(a)
3 return L
4
5 >>> print f(1)
6 >>> print f(2)
7 >>> print f(3)
1 [1]
2 [1, 2]
3 [1, 2, 3]
Default Argument Values (2)
Default values are evaluated at the point of function definition inthe defining scope.
1 >>> i = 5
2 >>> def f(arg=i):
3 ... print arg
4 >>> i = 6
5 >>> f()
1 5
Important warning: default values are evaluated only once.
1 def f(a, L=[]):
2 L.append(a)
3 return L
4
5 >>> print f(1)
6 >>> print f(2)
7 >>> print f(3)
1 [1]
2 [1, 2]
3 [1, 2, 3]
Default Argument Values (2)
Default values are evaluated at the point of function definition inthe defining scope.
1 >>> i = 5
2 >>> def f(arg=i):
3 ... print arg
4 >>> i = 6
5 >>> f()
1 5
Important warning: default values are evaluated only once.
1 def f(a, L=[]):
2 L.append(a)
3 return L
4
5 >>> print f(1)
6 >>> print f(2)
7 >>> print f(3)
1 [1]
2 [1, 2]
3 [1, 2, 3]
Default Argument Values (2)
Default values are evaluated at the point of function definition inthe defining scope.
1 >>> i = 5
2 >>> def f(arg=i):
3 ... print arg
4 >>> i = 6
5 >>> f()
1 5
Important warning: default values are evaluated only once.
1 def f(a, L=[]):
2 L.append(a)
3 return L
4
5 >>> print f(1)
6 >>> print f(2)
7 >>> print f(3)
1 [1]
2 [1, 2]
3 [1, 2, 3]
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.
Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Invalid function calls:
I opera(title=’Romeo and Juliet’,’Shakespeare’,’Tragedy’)
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’,year=1596)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Invalid function calls:
I opera(title=’Romeo and Juliet’,’Shakespeare’,’Tragedy’)
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’,year=1596)
Keyword Arguments
Functions can also be called using keyword arguments in the formkwarg=value.
1 def opera(title , author , type):
2 print title
3 print "-- a ", type , "written by", author
Keyword arguments can only be used after positional arguments.Valid function calls:
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’)
I opera(title=’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
I opera(’Romeo and Juliet’,type=’Tragedy’,author=’Shakespeare’)
Invalid function calls:
I opera(title=’Romeo and Juliet’,’Shakespeare’,’Tragedy’)
I opera(’Romeo and Juliet’, ’Shakespeare’,’Tragedy’,year=1596)
**keywords Arguments
When a final formal parameter of the form **name is present, itreceives a dictionary containing all keyword arguments except forthose corresponding to another formal parameter.
1 def cheeseshop(kind , **info):
2 print "-- Do you have any", kind , "?"
3 print "-- I am sorry , we are all out of", kind
4 print "-" * 40
5 keys = sorted(info.keys ())
6 for kw in keys:
7 print kw , ":", info[kw]
It could be called like this:
1 >>> cheeseshop("Limburger", shopkeeper=’Michael Palin’,
2 client="John", sketch="Cheese Shop Sketch")
1 -- Do you have any Limburger ?
2 -- I am sorry , we are all out of Limburger
3 ----------------------------------------
4 client : John
5 shopkeeper : Michael Palin
6 sketch : Cheese Shop Sketch
**keywords Arguments
When a final formal parameter of the form **name is present, itreceives a dictionary containing all keyword arguments except forthose corresponding to another formal parameter.
1 def cheeseshop(kind , **info):
2 print "-- Do you have any", kind , "?"
3 print "-- I am sorry , we are all out of", kind
4 print "-" * 40
5 keys = sorted(info.keys ())
6 for kw in keys:
7 print kw , ":", info[kw]
It could be called like this:
1 >>> cheeseshop("Limburger", shopkeeper=’Michael Palin’,
2 client="John", sketch="Cheese Shop Sketch")
1 -- Do you have any Limburger ?
2 -- I am sorry , we are all out of Limburger
3 ----------------------------------------
4 client : John
5 shopkeeper : Michael Palin
6 sketch : Cheese Shop Sketch
**keywords Arguments
When a final formal parameter of the form **name is present, itreceives a dictionary containing all keyword arguments except forthose corresponding to another formal parameter.
1 def cheeseshop(kind , **info):
2 print "-- Do you have any", kind , "?"
3 print "-- I am sorry , we are all out of", kind
4 print "-" * 40
5 keys = sorted(info.keys ())
6 for kw in keys:
7 print kw , ":", info[kw]
It could be called like this:
1 >>> cheeseshop("Limburger", shopkeeper=’Michael Palin’,
2 client="John", sketch="Cheese Shop Sketch")
1 -- Do you have any Limburger ?
2 -- I am sorry , we are all out of Limburger
3 ----------------------------------------
4 client : John
5 shopkeeper : Michael Palin
6 sketch : Cheese Shop Sketch
Arbitrary Argument Lists (and unpacking)
The *name syntax is used to specify that a function can be calledwith an arbitrary number of arguments (zero or more).
1 def write_multiple_items(file , separator , *args):
2 file.write(separator.join(args))
3
4 >>> write_multiple_item(f, ’ ’, ’Hello’, ’world’)
You can also do the reverse: if you have all your arguments in a listor tuple, you can unpack them using the *-operator.
1 >>> range(3, 6)
2 [3, 4, 5]
3 >>> args = [3, 6]
4 >>> range(*args)
5 [3, 4, 5]
If you have a dictionary, you can use the **-operator.
1 >>> d = {’author ’: ’Shakespeare ’,
2 ’title’:’Romeo and Juliet ’, ’type’:’Tragedy ’}
3 >>> opera (**d)
Arbitrary Argument Lists (and unpacking)
The *name syntax is used to specify that a function can be calledwith an arbitrary number of arguments (zero or more).
1 def write_multiple_items(file , separator , *args):
2 file.write(separator.join(args))
3
4 >>> write_multiple_item(f, ’ ’, ’Hello’, ’world’)
You can also do the reverse: if you have all your arguments in a listor tuple, you can unpack them using the *-operator.
1 >>> range(3, 6)
2 [3, 4, 5]
3 >>> args = [3, 6]
4 >>> range(*args)
5 [3, 4, 5]
If you have a dictionary, you can use the **-operator.
1 >>> d = {’author ’: ’Shakespeare ’,
2 ’title’:’Romeo and Juliet ’, ’type’:’Tragedy ’}
3 >>> opera (**d)
Arbitrary Argument Lists (and unpacking)
The *name syntax is used to specify that a function can be calledwith an arbitrary number of arguments (zero or more).
1 def write_multiple_items(file , separator , *args):
2 file.write(separator.join(args))
3
4 >>> write_multiple_item(f, ’ ’, ’Hello’, ’world’)
You can also do the reverse: if you have all your arguments in a listor tuple, you can unpack them using the *-operator.
1 >>> range(3, 6)
2 [3, 4, 5]
3 >>> args = [3, 6]
4 >>> range(*args)
5 [3, 4, 5]
If you have a dictionary, you can use the **-operator.
1 >>> d = {’author ’: ’Shakespeare ’,
2 ’title’:’Romeo and Juliet ’, ’type’:’Tragedy ’}
3 >>> opera (**d)
Lambda Forms
With the lambda keyword, small anonymous functions can becreated.
1 def make_incrementor(n):
2 return lambda x: x + n
3
4 >>> f = make_incrementor (42)
5 >>> f(0)
6 42
7 >>> f(5)
8 47
I Any number of arguments: lambda a,b,c: a+b+c
I Only a single expression
I Can reference variables from the containing scope
Lambda Forms
With the lambda keyword, small anonymous functions can becreated.
1 def make_incrementor(n):
2 return lambda x: x + n
3
4 >>> f = make_incrementor (42)
5 >>> f(0)
6 42
7 >>> f(5)
8 47
I Any number of arguments: lambda a,b,c: a+b+c
I Only a single expression
I Can reference variables from the containing scope
Lambda Forms
With the lambda keyword, small anonymous functions can becreated.
1 def make_incrementor(n):
2 return lambda x: x + n
3
4 >>> f = make_incrementor (42)
5 >>> f(0)
6 42
7 >>> f(5)
8 47
I Any number of arguments: lambda a,b,c: a+b+c
I Only a single expression
I Can reference variables from the containing scope
Lambda Forms
With the lambda keyword, small anonymous functions can becreated.
1 def make_incrementor(n):
2 return lambda x: x + n
3
4 >>> f = make_incrementor (42)
5 >>> f(0)
6 42
7 >>> f(5)
8 47
I Any number of arguments: lambda a,b,c: a+b+c
I Only a single expression
I Can reference variables from the containing scope
Exercises
I Define a function max(), that returns the maximum valueamong those received as parameters. It can receive eithervalues as list or a list of values
1 >>> l = [1, 2, 3, 4, 3, 2, 1]
2 >>> max(l)
3 4
4 >>> max(3, 4, 5, 6, 2, 3, 4)
5 6
I Define a function histogram() that takes a string as firstparameter, then an arbitrary number of parameters in theform bin_label=frequency and prints the relative histogram onthe screen
1 >>> histogram("Population of Pincoland",
2 2000=10 , 2005=15 , 2010=12)
3 Population of Pincoland
4 2000 **********
5 2005 ***************
6 2010 ************
Methods of list Objects
I list.append(x), adds x as last element
I list.extend(L), the same as list + L
I list.insert(i, x), inserts x before the element at position i
I list.remove(x), removes the first occurrence of x
I list.pop([i]), removes the last (or i-th) element
I list.index(x), returns the position of x (first occurrence)
I list.count(x), counts the occurrences of x
I list.sort(), sorts the list in place
I list.reverse(), reverses the elements of the list, in place
Reminder: lists (square brackets) are mutable objects, tuples(standard brackets) are immutable objects.
Methods of list Objects
I list.append(x), adds x as last element
I list.extend(L), the same as list + L
I list.insert(i, x), inserts x before the element at position i
I list.remove(x), removes the first occurrence of x
I list.pop([i]), removes the last (or i-th) element
I list.index(x), returns the position of x (first occurrence)
I list.count(x), counts the occurrences of x
I list.sort(), sorts the list in place
I list.reverse(), reverses the elements of the list, in place
Reminder: lists (square brackets) are mutable objects, tuples(standard brackets) are immutable objects.
filter, reduce...
I filter(function, sequence), returns a sequence consisting ofthose items from the sequence for which function(item) is true
1 def f(x):
2 return x % 2 != 0 and x % 3 != 0
3 >>> filter(f, range(2, 25))
4 [5, 7, 11, 13, 17, 19, 23]
I reduce(function, sequence), returns a single value constructedby calling the binary function on the first two items of thesequence, then on the result and the next item, and so on
1 def add(x, y):
2 return x + y
3
4 >>> reduce(add , range(1, 11))
5 55
I reduce(function, sequence, start_value), same as before, butuse start_value as first parameter for the first run
filter, reduce...
I filter(function, sequence), returns a sequence consisting ofthose items from the sequence for which function(item) is true
1 def f(x):
2 return x % 2 != 0 and x % 3 != 0
3 >>> filter(f, range(2, 25))
4 [5, 7, 11, 13, 17, 19, 23]
I reduce(function, sequence), returns a single value constructedby calling the binary function on the first two items of thesequence, then on the result and the next item, and so on
1 def add(x, y):
2 return x + y
3
4 >>> reduce(add , range(1, 11))
5 55
I reduce(function, sequence, start_value), same as before, butuse start_value as first parameter for the first run
filter, reduce...
I filter(function, sequence), returns a sequence consisting ofthose items from the sequence for which function(item) is true
1 def f(x):
2 return x % 2 != 0 and x % 3 != 0
3 >>> filter(f, range(2, 25))
4 [5, 7, 11, 13, 17, 19, 23]
I reduce(function, sequence), returns a single value constructedby calling the binary function on the first two items of thesequence, then on the result and the next item, and so on
1 def add(x, y):
2 return x + y
3
4 >>> reduce(add , range(1, 11))
5 55
I reduce(function, sequence, start_value), same as before, butuse start_value as first parameter for the first run
filter, reduce...
I filter(function, sequence), returns a sequence consisting ofthose items from the sequence for which function(item) is true
1 def f(x):
2 return x % 2 != 0 and x % 3 != 0
3 >>> filter(f, range(2, 25))
4 [5, 7, 11, 13, 17, 19, 23]
I reduce(function, sequence), returns a single value constructedby calling the binary function on the first two items of thesequence, then on the result and the next item, and so on
1 def add(x, y):
2 return x + y
3
4 >>> reduce(add , range(1, 11))
5 55
I reduce(function, sequence, start_value), same as before, butuse start_value as first parameter for the first run
... and map
I map(function, sequence), calls function(item) for each of thesequence’s items and returns a list of the return values
1 def cube(x):
2 return x*x*x
3 >>> map(cube , range(1, 11))
4 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
I More than one sequence may be passed; the function mustthen have as many arguments as there are sequences, and thesequences must have the same length
1 def add(x, y):
2 return x + y
3
4 >>> map(add , range(8), range (8 ,16))
5 [8, 10, 12, 14, 16, 18, 20, 22]
... and map
I map(function, sequence), calls function(item) for each of thesequence’s items and returns a list of the return values
1 def cube(x):
2 return x*x*x
3 >>> map(cube , range(1, 11))
4 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
I More than one sequence may be passed; the function mustthen have as many arguments as there are sequences, and thesequences must have the same length
1 def add(x, y):
2 return x + y
3
4 >>> map(add , range(8), range (8 ,16))
5 [8, 10, 12, 14, 16, 18, 20, 22]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensions
1 >>> squares = []
2 >>> for x in range (10):
3 ... squares.append(x**2)
4 ...
5 >>> squares
6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List comprehensions provide a concise way to create lists.
1 >>> squares = [x**2 for x in range (10)]
Can you do it with map ?
1 >>> squares = map(lambda x: x**2, range (10))
A listcomp consists of square brackets containing an expressionfollowed by a for clause, then zero or more for or if clauses.
1 >>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Matrix transpose with Nested List Comprehensions
Provide a function transpose(matrix) that returns the transpose ofthe matrix received as parameter, represented as an array of rows.
1 >>> a_matrix = [
2 ... [1, 2, 3, 4],
3 ... [5, 6, 7, 8],
4 ... [9, 10, 11, 12],
5 ... ]
1 def transpose(matrix ):
2 transposed = []
3 for i in range(len(matrix [0])):
4 transposed_row = []
5 for row in matrix:
6 transposed_row.append(row[i])
7 transposed.append(transposed_row)
8 return transposed
1 def transpose(matrix ):
2 cols = len(matrix [0])
3 return [[row[i] for row in matrix] for i in range(cols)]
Matrix transpose with Nested List Comprehensions
Provide a function transpose(matrix) that returns the transpose ofthe matrix received as parameter, represented as an array of rows.
1 >>> a_matrix = [
2 ... [1, 2, 3, 4],
3 ... [5, 6, 7, 8],
4 ... [9, 10, 11, 12],
5 ... ]
1 def transpose(matrix ):
2 transposed = []
3 for i in range(len(matrix [0])):
4 transposed_row = []
5 for row in matrix:
6 transposed_row.append(row[i])
7 transposed.append(transposed_row)
8 return transposed
1 def transpose(matrix ):
2 cols = len(matrix [0])
3 return [[row[i] for row in matrix] for i in range(cols)]
Matrix transpose with Nested List Comprehensions
Provide a function transpose(matrix) that returns the transpose ofthe matrix received as parameter, represented as an array of rows.
1 >>> a_matrix = [
2 ... [1, 2, 3, 4],
3 ... [5, 6, 7, 8],
4 ... [9, 10, 11, 12],
5 ... ]
1 def transpose(matrix ):
2 transposed = []
3 for i in range(len(matrix [0])):
4 transposed_row = []
5 for row in matrix:
6 transposed_row.append(row[i])
7 transposed.append(transposed_row)
8 return transposed
1 def transpose(matrix ):
2 cols = len(matrix [0])
3 return [[row[i] for row in matrix] for i in range(cols)]
Exercises
I Using reduce(), write a function max() that takes a list ofnumbers and returns the largest one
I Write a program that maps a list of words into a list ofintegers representing the lengths of the corresponding words
I Write a function find_longest_word() that takes a list of wordsand returns the length of the longest one
I Write a function remove_odd_words() that takes a list of wordsand returns a list of those that have an even length (usefilter())
Looping Techniques (1)
I enumerate(L), gets the position index and corresponding value
1 >>> for i, v in enumerate ([’tic’, ’tac’, ’toe’]):
2 ... print i, v
3 ...
4 0 tic
5 1 tac
6 2 toe
I zip(), pairs entries of two or more sequences
1 >>> primes = [2, 3, 5, 7, 11, 13, 17]
2 >>> squares = [x**2 for x in primes]
3 >>> for p, s in zip(primes , squares ):
4 ... print ’{0} squared is {1}.’.format(p, s)
5 ...
6 2 squared is 4
7 3 squared is 9
8 ...
Looping Techniques (1)
I enumerate(L), gets the position index and corresponding value
1 >>> for i, v in enumerate ([’tic’, ’tac’, ’toe’]):
2 ... print i, v
3 ...
4 0 tic
5 1 tac
6 2 toe
I zip(), pairs entries of two or more sequences
1 >>> primes = [2, 3, 5, 7, 11, 13, 17]
2 >>> squares = [x**2 for x in primes]
3 >>> for p, s in zip(primes , squares ):
4 ... print ’{0} squared is {1}.’.format(p, s)
5 ...
6 2 squared is 4
7 3 squared is 9
8 ...
Looping Techniques (1)
I enumerate(L), gets the position index and corresponding value
1 >>> for i, v in enumerate ([’tic’, ’tac’, ’toe’]):
2 ... print i, v
3 ...
4 0 tic
5 1 tac
6 2 toe
I zip(), pairs entries of two or more sequences
1 >>> primes = [2, 3, 5, 7, 11, 13, 17]
2 >>> squares = [x**2 for x in primes]
3 >>> for p, s in zip(primes , squares ):
4 ... print ’{0} squared is {1}.’.format(p, s)
5 ...
6 2 squared is 4
7 3 squared is 9
8 ...
Looping Techniques (2)
I reversed(), reverses the order of the items
1 >>> for i in reversed(range(1, 6, 2)):
2 ... print i
3 ...
4 5
5 3
6 1
I sorted(), returns a new sorted list
1 >>> basket = [’apple’, ’orange ’, ’apple ’,
2 ... ’pear’, ’orange ’, ’banana ’]
3 >>> for f in sorted(set(basket )):
4 ... print f
5 ...
6 apple
7 banana
8 orange
9 pear
Looping Techniques (2)
I reversed(), reverses the order of the items
1 >>> for i in reversed(range(1, 6, 2)):
2 ... print i
3 ...
4 5
5 3
6 1
I sorted(), returns a new sorted list
1 >>> basket = [’apple’, ’orange ’, ’apple ’,
2 ... ’pear’, ’orange ’, ’banana ’]
3 >>> for f in sorted(set(basket )):
4 ... print f
5 ...
6 apple
7 banana
8 orange
9 pear
Looping Techniques (3)
I dict.iteritems(), accesses keys and values of a dictionary atthe same time
1 >>> knights = {’gallahad ’: ’pure’, ’robin’: ’brave’}
2 >>> for k, v in knights.iteritems ():
3 ... print k, ’the’, v
4 ...
5 gallahad the pure
6 robin the brave
I It is recommended that you first make a copy of a list if youwant to modify it during iteration. Slices are very convenientfor this
1 >>> words = [’cat’, ’window ’, ’defenestrate ’]
2 >>> for w in words [:]:
3 ... if len(w) > 6:
4 ... words.insert(0, w)
5 ...
6 >>> words
7 [’defenestrate ’, ’cat’, ’window ’, ’defenestrate ’]
Looping Techniques (3)
I dict.iteritems(), accesses keys and values of a dictionary atthe same time
1 >>> knights = {’gallahad ’: ’pure’, ’robin’: ’brave’}
2 >>> for k, v in knights.iteritems ():
3 ... print k, ’the’, v
4 ...
5 gallahad the pure
6 robin the brave
I It is recommended that you first make a copy of a list if youwant to modify it during iteration. Slices are very convenientfor this
1 >>> words = [’cat’, ’window ’, ’defenestrate ’]
2 >>> for w in words [:]:
3 ... if len(w) > 6:
4 ... words.insert(0, w)
5 ...
6 >>> words
7 [’defenestrate ’, ’cat’, ’window ’, ’defenestrate ’]
Iterators
1 for x in l:
2 print x
1 it = iter(l)
2 while True:
3 try:
4 x = it.next()
5 print x
6 except StopIteration:
7 break
8 del it
I The iter() function creates an iterator: an object that has anext() method, which returns the next element in the list if itexists, otherwise it “raises” a StopIteration exception.
I Fully customizable using classes: you can decide how yourobject will “iterate” in a for loop!
Iterators
1 for x in l:
2 print x
1 it = iter(l)
2 while True:
3 try:
4 x = it.next()
5 print x
6 except StopIteration:
7 break
8 del it
I The iter() function creates an iterator: an object that has anext() method, which returns the next element in the list if itexists, otherwise it “raises” a StopIteration exception.
I Fully customizable using classes: you can decide how yourobject will “iterate” in a for loop!
Iterators
1 for x in l:
2 print x
1 it = iter(l)
2 while True:
3 try:
4 x = it.next()
5 print x
6 except StopIteration:
7 break
8 del it
I The iter() function creates an iterator: an object that has anext() method, which returns the next element in the list if itexists, otherwise it “raises” a StopIteration exception.
I Fully customizable using classes: you can decide how yourobject will “iterate” in a for loop!
Iterators
1 for x in l:
2 print x
1 it = iter(l)
2 while True:
3 try:
4 x = it.next()
5 print x
6 except StopIteration:
7 break
8 del it
I The iter() function creates an iterator: an object that has anext() method, which returns the next element in the list if itexists, otherwise it “raises” a StopIteration exception.
I Fully customizable using classes: you can decide how yourobject will “iterate” in a for loop!
Generators
I Simple and powerful tool for creating iterators
I Written like regular functions but use yield instead of return
1 def reverse(data):
2 for index in range(len(data)-1, -1, -1):
3 yield data[index]
I Iterators are automatically created from function definition
1 >>> for char in reverse(’golf’):
2 ... print char
3 ...
4 f
5 l
6 o
7 g
I Local variables and execution state are saved betweensubsequent calls of next()
Generators
I Simple and powerful tool for creating iterators
I Written like regular functions but use yield instead of return
1 def reverse(data):
2 for index in range(len(data)-1, -1, -1):
3 yield data[index]
I Iterators are automatically created from function definition
1 >>> for char in reverse(’golf’):
2 ... print char
3 ...
4 f
5 l
6 o
7 g
I Local variables and execution state are saved betweensubsequent calls of next()
Generators
I Simple and powerful tool for creating iterators
I Written like regular functions but use yield instead of return
1 def reverse(data):
2 for index in range(len(data)-1, -1, -1):
3 yield data[index]
I Iterators are automatically created from function definition
1 >>> for char in reverse(’golf’):
2 ... print char
3 ...
4 f
5 l
6 o
7 g
I Local variables and execution state are saved betweensubsequent calls of next()
Generators
I Simple and powerful tool for creating iterators
I Written like regular functions but use yield instead of return
1 def reverse(data):
2 for index in range(len(data)-1, -1, -1):
3 yield data[index]
I Iterators are automatically created from function definition
1 >>> for char in reverse(’golf’):
2 ... print char
3 ...
4 f
5 l
6 o
7 g
I Local variables and execution state are saved betweensubsequent calls of next()
Generators
I Simple and powerful tool for creating iterators
I Written like regular functions but use yield instead of return
1 def reverse(data):
2 for index in range(len(data)-1, -1, -1):
3 yield data[index]
I Iterators are automatically created from function definition
1 >>> for char in reverse(’golf’):
2 ... print char
3 ...
4 f
5 l
6 o
7 g
I Local variables and execution state are saved betweensubsequent calls of next()
Generator Expressions
Generators created like list comprehensions, but without squarebrackets.
1 >>> sum(i*i for i in range (10))
2 285
1 >>> xvec = [10, 20, 30]
2 >>> yvec = [7, 5, 3]
3 >>> sum(x*y for x,y in zip(xvec , yvec))
4 260
1 >>> from math import pi, sin
2 >>> sine_table = dict((x, sin(x*pi /180))
3 ... for x in range(0, 91))
1 >>> unique_words = set(word for line in page
2 ... for word in line.split ())
1 >>> data = ’golf’
2 >>> list(data[i] for i in range(len(data)-1,-1,-1))
3 [’f’, ’l’, ’o’, ’g’]
Generator Expressions
Generators created like list comprehensions, but without squarebrackets.
1 >>> sum(i*i for i in range (10))
2 285
1 >>> xvec = [10, 20, 30]
2 >>> yvec = [7, 5, 3]
3 >>> sum(x*y for x,y in zip(xvec , yvec))
4 260
1 >>> from math import pi, sin
2 >>> sine_table = dict((x, sin(x*pi /180))
3 ... for x in range(0, 91))
1 >>> unique_words = set(word for line in page
2 ... for word in line.split ())
1 >>> data = ’golf’
2 >>> list(data[i] for i in range(len(data)-1,-1,-1))
3 [’f’, ’l’, ’o’, ’g’]
Generator Expressions
Generators created like list comprehensions, but without squarebrackets.
1 >>> sum(i*i for i in range (10))
2 285
1 >>> xvec = [10, 20, 30]
2 >>> yvec = [7, 5, 3]
3 >>> sum(x*y for x,y in zip(xvec , yvec))
4 260
1 >>> from math import pi, sin
2 >>> sine_table = dict((x, sin(x*pi /180))
3 ... for x in range(0, 91))
1 >>> unique_words = set(word for line in page
2 ... for word in line.split ())
1 >>> data = ’golf’
2 >>> list(data[i] for i in range(len(data)-1,-1,-1))
3 [’f’, ’l’, ’o’, ’g’]
Generator Expressions
Generators created like list comprehensions, but without squarebrackets.
1 >>> sum(i*i for i in range (10))
2 285
1 >>> xvec = [10, 20, 30]
2 >>> yvec = [7, 5, 3]
3 >>> sum(x*y for x,y in zip(xvec , yvec))
4 260
1 >>> from math import pi, sin
2 >>> sine_table = dict((x, sin(x*pi /180))
3 ... for x in range(0, 91))
1 >>> unique_words = set(word for line in page
2 ... for word in line.split ())
1 >>> data = ’golf’
2 >>> list(data[i] for i in range(len(data)-1,-1,-1))
3 [’f’, ’l’, ’o’, ’g’]
Generator Expressions
Generators created like list comprehensions, but without squarebrackets.
1 >>> sum(i*i for i in range (10))
2 285
1 >>> xvec = [10, 20, 30]
2 >>> yvec = [7, 5, 3]
3 >>> sum(x*y for x,y in zip(xvec , yvec))
4 260
1 >>> from math import pi, sin
2 >>> sine_table = dict((x, sin(x*pi /180))
3 ... for x in range(0, 91))
1 >>> unique_words = set(word for line in page
2 ... for word in line.split ())
1 >>> data = ’golf’
2 >>> list(data[i] for i in range(len(data)-1,-1,-1))
3 [’f’, ’l’, ’o’, ’g’]