Helpful Functions¶
This page contains a collection of functions that you might find useful during this course.
Built-in Functions¶
This is a living list that will expand over the course of the semester.
print
¶
The print()
function allows you to output text to the console
while a program is running.
In a Grasshopper script node, instead of printing to the console, any printed text
gets sent to the out
pin, which can be viewed with a Panel.
- print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
- sep
string inserted between values, default a space.
- end
string appended after the last value, default a newline.
- file
a file-like object (stream); defaults to the current sys.stdout.
- flush
whether to forcibly flush the stream.
Note how print
is variadic. You can supply as many arguments as you want to it,
and each argument will be converted to a string using that object’s __str__()
method. The stringified arguments will then be sent to the output stream, separated
by the sep
argument, which is keyword-only. In the case of a Grasshopper script node,
the default output stream is captured into the out
pin.
len
¶
The len()
function returns the size of a collection, or any
object that has defined the __len__
method.
- len(obj, /)
Return the number of items in a container.
max
¶
The max()
function accepts items that support
“rich” comparison using <
, <=
, ==
, >=
, and !=
. Multiple versions
can be used:
- max(iterable, *[, default=obj, key=func]) value
- max(arg1, arg2, *args, *[, key=func]) value
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.
The second version is variadic and can be provided with as many positional inputs as you’d like. If, instead, an iterable is provided, all items within that iterable must be comparable with the rich comparison operators.
The keyword-only parameter key
accepts a function that takes in a single input
and returns a value that is richly comparable. With a key
, the output of the function
is instead the item, x
, from the input that has the maximum key(x)
. This can
be used, for example, to compute an “argmax”, the index of the maximal item:
def collection_at_index(idx):
return collection[idx]
argmax = max(range(len(collection)), key=collection_at_index)
Note how collection_at_index
is passed into key
without using parentheses
to call it. This supplies the function itself to key
instead of an output from
the function.
min
¶
The min()
function accepts items that support
“rich” comparison using <
, <=
, ==
, >=
, and !=
. Multiple versions
can be used:
- min(iterable, *[, default=obj, key=func]) value
- min(arg1, arg2, *args, *[, key=func]) value
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument.
The second version is variadic and can be provided with as many positional inputs as you’d like. If, instead, an iterable is provided, all items within that iterable must be comparable with the rich comparison operators.
The keyword-only parameter key
accepts a function that takes in a single input
and returns a value that is richly comparable. With a key
, the output of the function
is instead the item, x
, from the input that has the minimum key(x)
. This can
be used, for example, to compute an “argmax”, the index of the minimal item:
def collection_at_index(idx):
return collection[idx]
argmax = min(range(len(collection)), key=collection_at_index)
Note how collection_at_index
is passed into key
without using parentheses
to call it. This supplies the function itself to key
instead of an output from
the function.
sorted
¶
- sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
abs
¶
- abs(x, /)
Return the absolute value of the argument.
round
¶
- round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
reversed
¶
The reversed()
function can be used to reverse a sequence,
or any object that has defined the __reversed__
method.
- reversed(sequence, /)
Return a reverse iterator over the values of the given sequence.
Warning
reversed()
does not return a sequence. It returns something
that can be iterated over with a for
loop, but it cannot be indexed. If you need
a reversed version of your sequence that can be indexed, use a slice, as shown in
the Slicing Examples.
range
¶
- range(stop) range object
- range(start, stop[, step]) range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Useful in for
loops.
zip
¶
- zip(*iterables, strict=False) zip object
>>> list(zip('abcdefg', range(3), range(4))) [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted.
If strict is true and one of the arguments is exhausted before the others, raise a ValueError.
Useful in for
loops in conjunction with tuple unpacking:
for item1, item2 in zip(collection1, collection2):
...
enumerate
¶
- enumerate(iterable, start=0)
Return an enumerate object.
- iterable
an object supporting iteration
The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument.
- enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), …
Useful in for
loops in conjunction with tuple unpacking:
for idx, item in enumerate(collection):
...
Type Conversions¶
Many built-in types can be converted to one another by passing them to the new type’s
constructor. For example, to convert something to a string, use the
str()
. To convert something to an integer, use the
int()
. If the conversion fails, an error will be
raised.
- class str(object='')
- class str(bytes_or_buffer[, encoding[, errors]]) str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- class int([x])
- class int(x, base=10) integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- class float(x=0, /)
Convert a string or number to a floating-point number, if possible.
- class bool(x)
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
Doing Math¶
Be sure to check out the math
package if you need to do
math beyond simple arithmetic operations! Click on the math
to
proceed to the documentation.
from math import ...
# Where "..." is a comma-separated list of things you want to import
or
import math
# Where what you want can be accessed like "math.whatever"
String Operations¶
See String Methods.
Important to Remember
join
lower
upper
split
strip
Common Sequence Operations¶
See Common Sequence Operations.
Important to Remember
Containment tests
Concatenation
Indexing and slicing
Mutable Sequence Operations¶
See Mutable Sequence Operations.
Important to Remember
append
insert
pop
remove
Set Operations¶
See Set Types.
Important to Remember
add
remove
union
,intersection
,difference
, andsymmetric_difference
issubset
andissuperset
Dictionary Operations¶
See Mapping Types.
Important to Remember
keys
values
items
get