Parameters in Python
- Protokoll
from math import floor
help( floor )
Help on built-in function floor in module math:
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
Ignoring », /« for now and using the third person, we read:
- A manual page
floor( x )
Returns the floor of x as an Integral.
This is the largest integer <= x.
This means: »f« has a parameter whose name is »x«.
The documentation contains a proclamation and prose. (Both terms are used by me in this way, but are not part of common usage.)
The proclamation »floor( x )« gives us the name of the function and of the parameter.
The prose explains the semantics of the function.
Within the prose, the name of the parameter name stands for the argument value, so it says:
- A manual page
floor( x )
Returns the floor of the argument value as an Integral.
This is the largest integer <= the argument value.
The parameter name and the prose provide indications of the expected argument type.
- Conventions (not always reliable)
- »x« or »y«: a floating point number (class »float«)
- »i«, »j« oder »k«: an integral number (class »int«)
- »s«: a string (class »str«)
To learn more about entities of the standard library, you can always read The Python Library Reference Release 3.9.0 or web pages such as »https://docs.python.org/dev/library/math.html#math.floor« or a text book. The online-manual is intended to be an aide-mémoire for advanced readers.
/ »gamma« ⃖
Write a from import statement for the function from the »math« module, whose documentation is given below.
Then write a call to that function.
- documentation (reworked)
gamma( x, / )
- Returns the value of the gamma function for the value x.
This task is considered correctly solved if the written call to the function can be evaluated by a Python implementation without any error message.
Variadic Callables
Some callables can be called either without arguments or with an argument. They are called variadic, that is, they can be called with a varying number of arguments.
»input«
- Evaluation
print( input() )
abc
abc
- Evaluation
print( input( "Text? " ))
Text? abc
abc
»print«
- Evaluation
print( "abc" )
abc
- Evaluation
print()
- (blank line)
»int«
Whenever one of the standard classes is called, it always returns an object who has the called class as its type.
- Evaluation
int()
0
- Evaluation
int( 4 )
- 4
- Evaluation
int( 4.2 )
- 4
- Evaluation
int( "42" )
- 42
- Evaluation ⃖
int( "42" )+ 4
- 46
- Console transcript
int( 'abc' )
ValueError: invalid literal for int() with base 10: 'abc'
»float«
- Evaluation
int( "4.2" )+ 3.1
- 7.300000000000001
»bool«
- Protokoll
bool()
False
- Protokoll
bool( 0 )
False
- Protokoll
bool( 3 )
True
»str«
- Evaluation
str()
- ''
- Evaluation
print( str( "7.300000000000001" )+ "1" )
- 7.3000000000000011
- Evaluation ⃖
str( 4 )+ '4'
'44'
- Evaluation ⃖
print( 'x = ' + 2 )
TypeError
- Evaluation ⃖
print( 'x = ' + str( 2 ))
x = 2
»list«
- Evaluation
list()
[]
- Evaluation
"beispielsweise"
'beispielsweise'
list( _ )
['b', 'e', 'i', 's', 'p', 'i', 'e', 'l', 's', 'w', 'e', 'i', 's', 'e']
- Evaluation
list( "beispielsweise" )
['b', 'e', 'i', 's', 'p', 'i', 'e', 'l', 's', 'w', 'e', 'i', 's', 'e']
»dict«
- Evaluation
dict()
{}
Exercises
/ Exercise
Write an expression the evaluation of which will cause an integer to be read and double its value to be printed. (Here it can be taken for granted that the user always enters a numerical value between one and 1000).
- Protocol of an evaluation of the expression to be written
20
40
/ Exercise
Write an expression upon the evaluation of which two integers are read and their sum is printed. (Here it can be taken for granted that the user always enters a numerical value between one and 1000).
- Protocol of an evaluation of the expression to be written
20
30
50
Importing module names
- Syntax
module-name import statement
.------. .------.
--->( import )--->| Name |--->
'------' '------'Anweisung
.------------------------------.
---.--->| evaluation statement |---.--->
| '------------------------------' |
| .------------------------------. |
'--->| from import statement |---'
| '------------------------------' |
| .------------------------------. |
'--->| module-name import statement |---'
'------------------------------'
Semantics The name given will become available if such a module exists.
- Console transcript
from math import pi
math
NameError: name 'math' is not defined
- Console transcript
import math
math
<module 'math' (built-in)>
floor( 0 )
NameError: name 'floor' is not defined
The help system also can give help for modules.
- Console input
help( math )
- Console input
import builtins
help( builtins )
- Console transcript
__name__
'__main__'
- Console input
import __main__
help( __main__ )
»dir« applied to modules
We also can apply the variadic »dir« to modules.
- Console transcript
import math
from pprint import pprint
dir( math )
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
len( _ )
60
len( dir( math ))
60
vars( math )
{'__name__': 'math', '__doc__': 'This module provides access to the mathematical functions\ndefined by the C standard.', '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'dist': <built-in function dist>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'isqrt': <built-in function isqrt>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p':<built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'remainder': <built-in function remainder>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in functionsqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'prod': <built-in function prod>, 'perm': <built-in functionperm>, 'comb': <built-in function comb>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan}
pprint( _ )
{'__doc__': 'This module provides access to the mathematical functions\n'
'defined by the C standard.',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__name__': 'math',
'__package__': '',
'__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
'acos': <built-in function acos>,
'acosh': <built-in function acosh>,
'asin': <built-in function asin>,
'asinh': <built-in function asinh>,
'atan': <built-in function atan>,
'atan2': <built-in function atan2>,
'atanh': <built-in function atanh>,
'ceil': <built-in function ceil>,
'comb': <built-in function comb>,
'copysign': <built-in function copysign>,
'cos': <built-in function cos>,
'cosh': <built-in function cosh>,
'degrees': <built-in function degrees>,
'dist': <built-in function dist>,
'e': 2.718281828459045,
'erf': <built-in function erf>,
'erfc': <built-in function erfc>,
'exp': <built-in function exp>,
'expm1': <built-in function expm1>,
'fabs': <built-in function fabs>,
'factorial': <built-in function factorial>,
'floor': <built-in function floor>,
'fmod': <built-in function fmod>,
'frexp': <built-in function frexp>,
'fsum': <built-in function fsum>,
'gamma': <built-in function gamma>,
'gcd': <built-in function gcd>,
'hypot': <built-in function hypot>,
'inf': inf,
'isclose': <built-in function isclose>,
'isfinite': <built-in function isfinite>,
'isinf': <built-in function isinf>,
'isnan': <built-in function isnan>,
'isqrt': <built-in function isqrt>,
'ldexp': <built-in function ldexp>,
'lgamma': <built-in function lgamma>,
'log': <built-in function log>,
'log10': <built-in function log10>,
'log1p': <built-in function log1p>,
'log2': <built-in function log2>,
'modf': <built-in function modf>,
'nan': nan,
'perm': <built-in function perm>,
'pi': 3.141592653589793,
'pow': <built-in function pow>,
'prod': <built-in function prod>,
'radians': <built-in function radians>,
'remainder': <built-in function remainder>,
'sin': <built-in function sin>,
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'tau': 6.283185307179586,
'trunc': <built-in function trunc>}pprint( vars( math ))
{'__doc__': 'This module provides access to the mathematical functions\n'
'defined by the C standard.',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__name__': 'math',
'__package__': '',
'__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
'acos': <built-in function acos>,
'acosh': <built-in function acosh>,
'asin': <built-in function asin>,
'asinh': <built-in function asinh>,
'atan': <built-in function atan>,
'atan2': <built-in function atan2>,
'atanh': <built-in function atanh>,
'ceil': <built-in function ceil>,
'comb': <built-in function comb>,
'copysign': <built-in function copysign>,
'cos': <built-in function cos>,
'cosh': <built-in function cosh>,
'degrees': <built-in function degrees>,
'dist': <built-in function dist>,
'e': 2.718281828459045,
'erf': <built-in function erf>,
'erfc': <built-in function erfc>,
'exp': <built-in function exp>,
'expm1': <built-in function expm1>,
'fabs': <built-in function fabs>,
'factorial': <built-in function factorial>,
'floor': <built-in function floor>,
'fmod': <built-in function fmod>,
'frexp': <built-in function frexp>,
'fsum': <built-in function fsum>,
'gamma': <built-in function gamma>,
'gcd': <built-in function gcd>,
'hypot': <built-in function hypot>,
'inf': inf,
'isclose': <built-in function isclose>,
'isfinite': <built-in function isfinite>,
'isinf': <built-in function isinf>,
'isnan': <built-in function isnan>,
'isqrt': <built-in function isqrt>,
'ldexp': <built-in function ldexp>,
'lgamma': <built-in function lgamma>,
'log': <built-in function log>,
'log10': <built-in function log10>,
'log1p': <built-in function log1p>,
'log2': <built-in function log2>,
'modf': <built-in function modf>,
'nan': nan,
'perm': <built-in function perm>,
'pi': 3.141592653589793,
'pow': <built-in function pow>,
'prod': <built-in function prod>,
'radians': <built-in function radians>,
'remainder': <built-in function remainder>,
'sin': <built-in function sin>,
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'tau': 6.283185307179586,
'trunc': <built-in function trunc>}- Names from the module »builtins« (output manually reformatted)
import builtins
dir( builtins )
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- Names from the module »__main__« (output manually reformatted)
import __main__
dir( __main__ )
['__annotations__', '__builtins__', '__doc__', '__loader__', '__main__', '__name__', '__package__', '__spec__' ]
(Output details may differ from Python implementation to Python implementation)
»dir« without arguments
»dir()« without arguments (within »__main__«) means the same as »dir( __main__ )« (after »import __main__«).
- Names from the module »__main__« (output manually reformatted) without any imports
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
The documentation of »dir«
The fact that »dir« is variadic, i.e., that the argument can be omitted, is expressed in the documentation of »dir« by writing the parameter name in brackets.
- Extract from the documentation
>>> help( dir )
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
»vars« with arguments
»vars« can be used ₍ˈsɪməlɚli₎ similarly to »dir«.
- Console transcript
import math
from pprint import pprint
pprint( vars( math ))
{'__doc__': 'This module provides access to the mathematical functions\n'
'defined by the C standard.',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__name__': 'math',
'__package__': '',
'__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
'acos': <built-in function acos>,
'acosh': <built-in function acosh>,
'asin': <built-in function asin>,
'asinh': <built-in function asinh>,
'atan': <built-in function atan>,
'atan2': <built-in function atan2>,
'atanh': <built-in function atanh>,
'ceil': <built-in function ceil>,
'comb': <built-in function comb>,
'copysign': <built-in function copysign>,
'cos': <built-in function cos>,
'cosh': <built-in function cosh>,
'degrees': <built-in function degrees>,
'dist': <built-in function dist>,
'e': 2.718281828459045,
'erf': <built-in function erf>,
'erfc': <built-in function erfc>,
'exp': <built-in function exp>,
'expm1': <built-in function expm1>,
'fabs': <built-in function fabs>,
'factorial': <built-in function factorial>,
'floor': <built-in function floor>,
'fmod': <built-in function fmod>,
'frexp': <built-in function frexp>,
'fsum': <built-in function fsum>,
'gamma': <built-in function gamma>,
'gcd': <built-in function gcd>,
'hypot': <built-in function hypot>,
'inf': inf,
'isclose': <built-in function isclose>,
'isfinite': <built-in function isfinite>,
'isinf': <built-in function isinf>,
'isnan': <built-in function isnan>,
'isqrt': <built-in function isqrt>,
'ldexp': <built-in function ldexp>,
'lgamma': <built-in function lgamma>,
'log': <built-in function log>,
'log10': <built-in function log10>,
'log1p': <built-in function log1p>,
'log2': <built-in function log2>,
'modf': <built-in function modf>,
'nan': nan,
'perm': <built-in function perm>,
'pi': 3.141592653589793,
'pow': <built-in function pow>,
'prod': <built-in function prod>,
'radians': <built-in function radians>,
'remainder': <built-in function remainder>,
'sin': <built-in function sin>,
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'tau': 6.283185307179586,
'trunc': <built-in function trunc>}
»type«
The class »type« returns the type of its argument. This can be used to confirm some information that has been given about types of expression.
- Evaluation
type( 9 )
<class 'int'>
- Evaluation
type( 9 )
<class 'int'>
- Evaluation
type( 9.2 )
<class 'float'>
- Evaluation
type( 'letters' )
<class 'str'>
- Evaluation
type( True )
<class 'bool'>
- Evaluation
type( None )
<class 'NoneType'>
- Evaluation
type( dir )
<class 'builtin_function_or_method'>
- Evaluation
type( dir() )
<class 'list'>
- Evaluation
type( lambda:9 )
<class 'function'>
- Evaluation
type( ( lambda:9 )() )
<class 'int'>
- Evaluation
import math
type( math )
<class 'module'>
- Evaluation
int( 4 )
4
type( _ )
<class 'int'>
- Evaluation
type( int( 4 ))
<class 'int'>
- Evaluation
type( int( 2.2 ))
<class 'int'>
- Evaluation
type( int( '4' ))
<class 'int'>
- Evaluation
type( float( '2.2' ))
<class 'float'>
- Evaluation
type( bool( 3 ))
<class 'bool'>
- Evaluation
type( str( 34.2 ))
<class 'str'>
›ord‹ and ›chr‹
- Evaluation
ord( 'A' )
65
- Evaluation
chr( 65 )
'A'
? Evaluation
Without using the computer, what is the value of »chr( ord( 'D' ))«?
? Evaluation
Without using the computer, what is the value of »ord( chr( 100 ))«?
/ Exercise
Write an expression upon the evaluation of which a character is read from the user and the ordinal number of that character is printed.
- Transcript of an evaluation of the expression to be written
A
65
/ Exercise
Write an expression upon the evaluation of which a number is read from the user and the character having this ordinal number is printed.
- Transcript of an evaluation of the expression to be written
65
A
Comments
Comments can be added to the end of the line, using a number sign »#« at the start of the line or after any token.
- Transcript
# comment
(keine Ausgabe)
- Evaluation
1 # the number one
1
Iterators
Some objects yield a value when the function »next« is applied to them. Those objects are called iterators.
- Console transcript
from multiprocessing.pool import job_counter
next( job_counter )
0
next( job_counter )
1
next( job_counter )
2
- Console transcript
from sys import stdin
"Eingabe = " + next( stdin )
abc
Eingabe = abc\n
Iterables
Some objects yield an iterator when the function »iter« is applied to them. Those objects are called iterables.
- Illustration
iter next
iterable --------------------> iterator --------------------> object
- Console transcript
iter( "abc" )
<str_iterator object …>
next( _ )
'a'
- Console transcript
next( iter( "abc" ))
'a'
- Illustration
iter next
"abc" --------------------> iterator --------------------> "a"- Console transcript
next( iter( "" ))
StopIteration
- Console transcript
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
iter( _ )
<list_iterator object …>
next( _ )
'__annotations__'
next( iter( dir() ))
'__annotations__'
- Illustration
iter next
[ '__annotations__', ... ] --------------------> Iterator --------------------> '__annotations__'
An iterator can only be used once, then it is exhausted.
An iterable can always yield a new iterator to have it traversed as often as needed.
? Practice question
What should be printed below?
- Console transcript
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
next( iter( next( iter( dir() ))))
- ?
Tuples
A tuple can collect all the values of an iterable into an object (the tuple).
- Console transcript
tuple( 'abc' )
('a', 'b', 'c')
type( _ )
<class 'tuple'>
type( tuple( 'abc' ))
<class 'tuple'>
String, lists and tuples are iterable.
While lists are printed in brackets, tuples are printed in parentheses.
- Console transcript
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
tuple( dir() )
('__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__')
type( dir() )
<class 'list'>
type( tuple( dir() ))
<class 'tuple'>
We don't need to know about other differences between lists and tuples for now.
»count« yields all natural numbers beginning at zero.
- Console transcript
from itertools import count
count()
count(0)
iter( _ )
count(0)
next( _ )
0
- Console transcript
from itertools import count
next( iter( count() ))
0
Warning An attempt to evaluate »tuple( count() )« might make your computer become unresponsive until it is restarted, which might cause loss of data! Don't do this!
? Practice question
Why is it possible that an attempt to evaluate »tuple( count() )« might make your computer become unresponsive?
»range«
A range objects requires relatively little memory, even when it represents a large range of numbers, because it only stores start value, the end value (and sometimes a possible step value).
»range( s, t )« is the range of integral numbers from «s » (inclusive) to «t » (exclusive).
»range( t )« is the range of integral numbers from «0» to «t ».
A range is an iterable, and when it is manifested as a tuple, then alle the values are really stored in this tuple!
- Console transcript
next( iter( range( 10 )))
0
- Console transcript
range( 3 )
range(0,3)
tuple( _ )
(0, 1, 2)
- Console transcript
tuple( range( 3 ))
(0, 1, 2)
- Console transcript
tuple( range( 10 ))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Warning Attempts to manifest too large a range of numbers may ₍rɪˈzʌlt₎ result in the computer having to be restarted at the risk of data loss!
/ Exercise
Print the numbers from 10 (inclusive) to 20 (inclusive) (as a tuple), but no other numbers.
/ Exercise
Print the numbers from 0 (inclusive) to 9999 (inclusive) (as a tuple), but no other numbers.
»sum«
»sum« accepts an iterable that yields numbers and returns the sum of all those numbers.
- Console transcript
sum( range( 10, 20 ))
145
/ Exercise
Determine the sum of all natural numbers up to 100 (inclusive).
»max«
»max« and »min« accept an iterable and return the maximum and minimum (respectively) of all the values yielded by the iterable.
For texts, a lexicographic order is used. What is further back in the lexicon is considered to be larger.
- Console transcript
min( "beispielsweise" )
'b'
max( "beispielsweise" )
'w'
- Console transcript
tuple( range( 20, 30 ))
(20, 21, 22, 23, 24, 25, 26, 27, 28, 29)
min( _ )
20
max( range( 20, 30 ))
29
- Console transcript
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
min( _ )
'__annotations__'
max( dir() )
'__spec__'
›sorted‹
The argument value of the function ›sorted‹ must be an iterable.
The function ›sorted‹ returns a list with the values of its argument object sorted in ascending order.
- Console transcript
sorted
<built-in function sorted>
sorted( dir() )
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
sorted( range( 10 ))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given examples are not quite convincing, since the argument objects are already sorted here. Since an str string is also iterable, we can use it as an example for a real sorting.
- Evaluation
sorted( "supercalifragilisticexpialidocious" )
['a', 'a', 'a', 'c', 'c', 'c', 'd', 'e', 'e', 'f', 'g', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'o', 'o', 'p', 'p', 'r', 'r', 's', 's', 's', 't', 'u', 'u', 'x']
Grouping iterables
A counter counts the occurences of values within all the values yielded by an iterable.
We now can see that the word “supercalifragilisticexpialidocious” contains four “i”, and the current director contains every word exactly once.
- Console transcript
"supercalifragilisticexpialidocious"
'supercalifragilisticexpialidocious'
from collections import Counter
Counter( _ )
Counter({'i': 7, 's': 3, 'c': 3, 'a': 3, 'l': 3, 'u': 2, 'p': 2, 'e': 2, 'r': 2, 'o': 2, 'f': 1, 'g': 1, 't': 1, 'x': 1, 'd': 1})
from pprint import pprint
pprint( _ )
Counter({'i': 7,
's': 3,
'c': 3,
'a': 3,
'l': 3,
'u': 2,
'p': 2,
'e': 2,
'r': 2,
'o': 2,
'f': 1,
'g': 1,
't': 1,
'x': 1,
'd': 1})- Console transcript (alternative version without »_«)
from pprint import pprint
from collections import Counter
pprint( Counter( "supercalifragilisticexpialidocious" ))
Counter({'i': 7,
's': 3,
'c': 3,
'a': 3,
'l': 3,
'u': 2,
'p': 2,
'e': 2,
'r': 2,
'o': 2,
'f': 1,
'g': 1,
't': 1,
'x': 1,
'd': 1})pprint( Counter( dir() ))
Counter({'Counter': 1,
'__annotations__': 1,
'__builtins__': 1,
'__doc__': 1,
'__loader__': 1,
'__name__': 1,
'__package__': 1,
'__spec__': 1,
'pprint': 1})
Lambda Parameters
A function that returns twice its argument value («x»).
- Evaluation
( lambda x: 2 * x )( 7 )
14
Syntax
- Syntax
lambda expression
.------------------------------.
| |
.------. | .---------------------. V .-. .------------.
--->( lambda )---'---| ordinary identifier |----'--->( : )--->| expression |--->
'------' '---------------------' '-' '------------'
An identifier is a word (made up of letters, digits and underscores, but not beginning with a digit), for example, »x_2«.
A keyword is a word that appears in the syntax of the language Python (in a rounded rectangle in a syntax diagram, like »lambda«),
An ordinary identifier is an identifier that is not a keyword, for example, »x_2« (again).
Semantics
When an expression such as »( lambda x: 2 * x )( 7 )« is being evaluated:
- An incarnation (copy) of the lambda object is created, where the parameter is bound to the value of the argument (in the given example, this is »lambda x: 2 * x« with »x« bound to «7».)
- Then the inner expression of this incarnation is evaluated (in the given example, »2 * x« is evaluated with »x« bound to «7», yielding «14».
Effectively, the argument value is substituted for the parameter name. »2 * x« → »2 * 7« (“β reduction”).
»lambda x« says “this is a function, and it has a parameter called »x«.”
Choice of the parameter name
The name of the parameter can be chosen freely or change („α conversion“, a refactor).
- Console transcript
( lambda x: 2 * x )( 7 )
14
- Console transcript
( lambda y: 2 * y )( 7 )
14
- Console transcript
( lambda number: 2 * number )( 7 )
14
The new parameter name, however, should not already be in use in the program (simplified).
Means of Simplification
»( lambda x: sqrt( x ))« is effectively the same as just »sqrt«.
- Console transcript
from math import sqrt # square root
( lambda x: sqrt( x ))( 16 )
4
- Console transcript
( sqrt )( 16 )
4
- Console transcript
sqrt( 16 )
4
Scope
The parameter name only is valid within its scope, which is the inner expression of the lambda expression.
- Console transcript (simplified)
( lambda x: x )( 3 )
3
x
NameError: name 'x' is not defined
- Console transcript (simplified)
( lambda x: x )( 3 )
3
x
NameError: name 'x' is not defined
Requirements for calls
When a lambda expression has a parameter, it has to be called with an argument expression.
- Console transcript (simplified)
( lambda x: x )()
TypeError: <lambda>() missing 1 required positional argument: 'x'
When a lambda expression has no parameter, it must not be called with an argument expression.
- Console transcript (simplified)
( lambda: 0 )( 2 )
TypeError: <lambda>() takes 0 positional arguments but 1 was given
»dir«
If ›dir‹ is called without any arguments, it returns the names of the binding table of the “environment” in which it is located. The environment (the scope) can be a module or a lambda expression.
Within a lambda expression, »dir« returns the parameter names.
- Console transcript
( lambda x: dir() )( 0 )
['x']
»vars«
»vars« also gives us the value to which the parameter name is bound.
- Console transcript
( lambda x: vars() )( 0 )
{'x': 0}
Rules for name lookup
If a name is used in the inner expression of a lambda expression, the Python implementation first searches for a value of the name in the binding table of the lambda object, then in the binding table of the module surrounding the expression, and finally in the module »builtins«.
- Evaluation of a name from »builtins«
( lambda x: quit )( 0 )
Use quit() or Ctrl-Z plus Return to exit
- Evaluation of a name from »__main__« (the current module)
from math import pi
( lambda x: pi )( 0 )
3.141592653589793
- Evaluation of a name from the lambda object
( lambda pi: pi )( 0 )
0
? Practice Questions
Can you predict the values of the following expressions?
- Expression
( lambda x: 4 )( 3 )
- Expression 1
( lambda x: x )( 9 )
- Expression 2
( lambda o: o )( 9 )
- Expression 3
( lambda x: 2 + x )( 3 )
- Expression 4
( lambda x: x / 2 )( 8 )
- Expression 5
( lambda x: x + x )( 10 + 2 )
- Expression 6
( lambda x: x * 'abc' +( 1 - x )* 'def' )( 1 )
- Expression 7
( lambda x: x * 'abc' +( 1 - x )* 'def' )( 0 )
- Expression 8 *
( lambda x: lambda: x )( 2 )()
- Expression 9 *
( lambda x: lambda y: x - y )( 5 )( 8 )
- Expression 10 *
( lambda f: f( 2 ))( lambda x: x * x )
- Expression 11 *
( lambda f: lambda x: f( x ))( lambda x: x * x )( 3 )
/ Exercise
Write a lambda expression into the console, so that the evaluations of »_( 2 )« and »_( 3 )« then print «4» and «9», respectively.
- Console transcript (extract)
lambda …
<function <lambda> at 0x000000000…>
_( 2 )
4
_( 3 )
9