Built-in functions ↩
Python comes with many built-in functions which are always available as part of the language. We’ve already seen some of them in the previous sections. This page gives an overview of the most important ones.
Type conversions
- type()
-
Returns the type of a given object:
>>> type('hello')
<type 'str'>
>>> type(1)
<type 'int'>
>>> type(33.3)
<type 'float'>
Python has several built-in functions to convert from one data type to another, these functions are object constructors. They have the same name as the data types, so it’s easy to remember them:
- str()
-
Transforms something into a string, or creates a new empty string if called without any argument:
>>> a = str(10) >>> a, type(a), len(a)
('10', <class 'str'>, 2)
>>> b = str() >>> b, type(b), len(b)
('', <class 'str'>, 0)
- list()
-
Transforms something into a list, or creates a new list if called without any argument:
>>> list('abcdefghijklmn')
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
>>> L = list() >>> L, type(L), len(L)
([], <class 'list'>, 0)
- dict()
-
Creates a dictionary from arguments (tuples, keyword arguments), or a new empty dictionary if called without any arguments:
>>> dict([('hello', 1), ('world', 2)]
{'hello': 1, 'world': 2}
>>> dict(hello=1, world=2)
{'hello': 1, 'world': 2}
>>> d = dict() >>> type(d), len(d), d
(<class 'dict'>, 0, {})
- float()
-
Transforms an integer or string into a floating point number:
>>> float(27)
27.0
When called without any argument,
float()
creates a new float with value0.0
:>>> float()
0.0
Conversion from string to float only works if the string looks like a number:
>>> float('27.0')
27.0
>>> float('27')
27.0
>>> float('27,0')
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: '27,0'
- bool()
-
Transforms any data type into a boolean value:
>>> bool(1)
True
>>> bool('')
False
When called without any argument,
bool()
returnsFalse
:>>> bool()
False
See testing truthiness for examples of conversions from other data types.
- set()
-
Creates a new set object from a collection:
>>> set('abracadabra')
{'r', 'b', 'c', 'a', 'd'}
>>> set([1, 5, 10, 50, 10, 5, 1])
{1, 10, 50, 5}
>>> set({'a': 5, 'b': 3, 'c': 1})
{'c', 'a', 'b'}
>>> set(((10, 20), (20, 25), (10, 20)))
{(20, 25), (10, 20)}
When called without any argument,
set()
creates a new empty set:>>> set()
set()
- tuple()
-
Creates a tuple from a collection:
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple({'a': 5, 'b': 3, 'c': 1})
('a', b', 'c')
When called without any argument,
tuple()
creates a new empty tuple:>>> tuple()
()
Collections and loops
- len()
-
Returns the number of items in a collection:
>>> L = ['A', 'B', [1, 2, 3], 'D'] >>> len(L)
4
>>> len('I will not buy this record, it is scratched.')
44
- range()
-
Returns an iterator which yields a sequence of numbers. It is typically used to repeat an action a number of times:
>>> range(0, 4)
range(0, 4)
>>> for i in range(4): ... i
0 1 2 3
- enumerate()
-
Returns an iterator which adds a counter to each item in a collection:
>>> L = ['Alpha', 'Bravo', 'Charlie', 'Delta'] >>> enumerate(L)
<enumerate object at 0x1039f6558>
>>> list(enumerate(L))
[(0, 'Alpha'), (1, 'Bravo'), (2, 'Charlie'), (3, 'Delta')]
The
enumerate()
function is typically used to loop over the items in a collection:>>> for index, item in enumerate(L): ... index, item
(0, 'Alpha') (1, 'Bravo') (2, 'Charlie') (3, 'Delta')
- sorted()
-
Returns a sorted copy of a given collection. This is useful if we need to do a sorted loop without actually sorting the collection:
>>> L = ['Mike', 'Bravo', 'Charlie', 'Tango', 'Alpha'] >>> for item in sorted(L): ... item
'Alpha' 'Bravo' 'Charlie' 'Mike' 'Tango'
- reversed()
-
The
reversed()
function is similar tosorted()
: it returns a copy of a given collection with the items in inverse order.>>> for item in reversed(L): ... item
'Alpha' 'Tango' 'Charlie' 'Bravo' 'Mike'
- zip()
-
Takes two separate lists, and produces a new list with pairs of values (one from each list):
>>> L1 = ['A', 'B', 'D', 'E', 'F', 'G', 'H', 'I'] >>> L2 = [1, 2, 3, 4, 5, 6] >>> zip(L1, L2)
<zip object at 0x1039f8608>
>>> list(zip(L1, L2))
[('A', 1), ('B', 2), ('D', 3), ('E', 4), ('F', 5), ('G', 6)]
The resulting list has the same number of items as the smallest of the two lists.
The
zip()
function can be used to create a dictionary from a list of keys and a list of values:>>> D = dict(zip(L1, L2)) >>> D
{'A': 1, 'B': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6}
- map()
-
Returns an iterator which applies a function to every item of a given collection. Use
list()
to convert the iterator into a list.>>> def square(n): ... return n*n ... >>> L1 = [13, 27, 4, 19, 22] >>> L2 = list(map(square, L1)) >>> >>> print(L2)
[169, 729, 16, 361, 484]
Expressions with
map()
can be rewritten using list comprehensions:>>> L2 = [square(n) for n in L1]
The
map()
function may also take multiple collections, and pass multiple arguments to the function at each iteration.>>> def calculate(v1, v2, v3): ... return v1 * v2 - v3 ... >>> L1 = [1, 2, 3, 4, 5] >>> L2 = [11, 12, 13, 14, 15, 16] >>> L3 = [21, 22, 23, 24, 25, 26, 27] >>> L4 = list(map(calculate, L1, L2, L3)) >>> >>> print(L4)
[-10, 2, 16, 32, 50]
If the given collections have different lengths, the iterator will stop when the shortest one (
L1
) reaches its end. - filter()
-
Takes a function and a collection as arguments, and returns an iterator which produces a list containing only those items from the original list for which the given function returns
True
.>>> def test(n): ... return n > 10 ... >>> L1 = [3, 21, 7, 9, 14, 33, 11, 8] >>> L2 = list(filter(test, L1)) >>> >>> print(L2)
[21, 14, 33, 11]
Expressions with
filter()
can also be written using list comprehensions:>>> L2 = [n for n in L1 if n > 10]
Numerical
Some built-in functions are useful when working with numbers:
- abs()
-
The
abs()
function returns the absolute value of a number:>>> abs(-100)
100
- sum()
-
The
sum()
function returns the sum of all numbers in a list:>>> L = [10, 300.7, 50, 33.1] >>> sum(L)
393.8
- min() and max()
-
The
min()
function returns the smallest number in a list of numbers:>>> min(L)
10
The
max()
function returns the largest number in a list of numbers:>>> max(L)
300.7
- round()
-
The
round()
function rounds a number to a given precision.When called without any argument,
round()
converts a float to the nearest integer:>>> round(3.1416)
3
If two multiples are equally close, rounding is done toward the even number:
>>> round(0.5)
0
>>> round(1.5)
2
The function can also take a second argument to specify the number of digits after the decimal point:
>>> round(3.141592653589793, 4)
3.1416
Boolean
- any()
-
Evaluates all statements in a collection and returns:
True
if at least one statement isTrue
False
if all statements areFalse
>>> any([0, 0, 0, 0])
False
>>> any([0, 0, 1, 0])
True
- all()
-
Evaluates all statements in a collection, and returns:
True
if all statements areTrue
False
if at least one statement isFalse
>>> all([0, 0, 0, 0])
False
>>> all([0, 0, 1, 0])
False
>>> all([1, 1, 1, 1])
True
Attributes
- dir()
-
Returns a list of names (attributes and methods) in a given object. This is useful to get an idea of how an object is structured and what it can do.
Here’s an example using
dir()
to view the contents of an imported module:>>> import math >>> dir(math)
['__doc__', '__file__', '__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', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
When called without any argument,
dir()
returns a list of names in the current local scope.If you’re starting a new interactive session in Terminal,
dir()
will return only private attributes and methods (with names starting with double underscores) which are made available by the Python language:>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
Variable names declared during the session are added to the local scope, and are included in
dir()
results too:>>> 'myVariable' in dir()
False
>>> myVariable = 120 >>> 'myVariable' in dir()
True
If you are scripting in RoboFont, you can use
dir()
to see that all the main fontParts.world objects are available out-of-the box in the Scripting Window:print(dir())
['AllFonts', 'CreateCursor', 'CurrentAnchors', 'CurrentComponents', 'CurrentContours', 'CurrentFont', 'CurrentGlyph', 'CurrentGuidelines', 'CurrentLayer', 'CurrentPoints', 'CurrentSegments', 'FontsList', 'NewFont', 'OpenFont', 'OpenWindow', 'RAnchor', 'RComponent', 'RContour', 'RFeatures', 'RFont', 'RGlyph', 'RGroups', 'RInfo', 'RKerning', '__builtins__', '__file__', '__name__', 'help']
- getattr()
-
Used to get the value of an object’s attribute. Instead of accessing the attribute directly, we pass the object and the attribute name to the
getattr()
function, and get a value back. This ‘indirect’ approach allows us to write code that is more abstract and more reflexive.Here’s a simple example using an open font in RoboFont. Let’s imagine that we want to print out some font info attributes. We could access them directly one by one, like this:
font = CurrentFont() print(font.info.familyName) print(font.info.styleName) print(font.info.openTypeNameDesigner)
RoboType Roman Frederik Berlaen
Using getattr()
, we can separate the definition of the attribute names from the retrieval of the values:
attrs = ['familyName', 'styleName', 'openTypeNameDesigner']
for attr in attrs:
print(getattr(font.info, attr))
- setattr()
-
The
setattr()
function is complementary togetattr()
– it allows us to set the value of an object’s attribute.Here’s an example script which sets some font info values in the current font. The font info is defined in a dictionary, but it could be coming from an external file or a dialog.
font = CurrentFont() fontInfo = { 'familyName' : 'MyFamily', 'styleName' : 'Black Italic', 'styleMapFamilyName' : 'Black', 'styleMapStyleName' : 'italic', } for attr, value in fontInfo.items(): setattr(font.info, attr, value)
There’s also a
delattr()
function to delete an attribute from an object.
Character encoding
- chr()
-
Returns a unicode character for a given unicode value (as a decimal number):
>>> chr(192)
'À'
- ord()
-
Does the opposite from
char()
– returns the unicode number for a given character:>>> ord('A')
65