Text
stringlengths
1
9.41k
These arguments will be wrapped up in a tuple (see Tuples and Sequences).
Before the variable number of arguments, zero or more normal arguments may occur. ``` def write_multiple_items(file, separator, *args): file.write(separator.join(args)) ``` Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are p...
Any formal parameters which occur after ----- the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments. ``` >>> def concat(*args, sep="/"): ...
return sep.join(args) ... >>> concat("earth", "mars", "venus") 'earth/mars/venus' >>> concat("earth", "mars", "venus", sep=".") 'earth.mars.venus' #### 4.7.4 Unpacking Argument Lists ``` The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requirin...
For instance, the built-in range() function expects separate start and stop arguments.
If they are not available separately, write the function call with the ``` *-operator to unpack the arguments out of a list or tuple: >>> list(range(3, 6)) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] ``` In the same fashi...
print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ...
print("E's", state, "!") ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it.
E's bleedin' demised ! #### 4.7.5 Lambda Expressions ``` Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b.
Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression.
Semantically, they are just syntactic sugar for a normal function definition.
Like nested function definitions, lambda functions can reference variables from the containing scope: ``` >>> def make_incrementor(n): ...
return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43 ``` The above example uses a lambda expression to return a function.
Another use is to pass a small function as an argument: ----- #### 4.7.6 Documentation Strings Here are some conventions about the content and formatting of documentation strings. The first line should always be a short, concise summary of the object’s purpose.
For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation).
This line should begin with a capital letter and end with a period. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc. The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired.
This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string.
(We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string.
Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped.
Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally). Here is an example of a multi-line docstring: ``` >>> def my_function(): ...
"""Do nothing, but document it. ... ... No, really, it doesn't do anything. ... """ ...
pass ... >>> print(my_function.__doc__) Do nothing, but document it. No, really, it doesn't do anything. #### 4.7.7 Function Annotations ``` Function annotations are completely optional metadata information about the types used by user-defined [functions (see PEP 3107 and PEP 484 for more information).](https://www...
Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation.
Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement.
The following example has a positional argument, a keyword argument, and the return value annotated: ``` >>> def f(ham: str, eggs: str = 'eggs') -> str: ...
print("Annotations:", f.__annotations__) ``` (continues on next page) ----- (continued from previous page) ``` ... print("Arguments:", ham, eggs) ...
return ham + ' and ' + eggs ... >>> f('spam') Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} Arguments: spam eggs 'spam and eggs' ### 4.8 Intermezzo: Coding Style ``` Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about _coding sty...
Most languages can be written (or more concise, formatted) in different styles; some are more_ readable than others.
Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that. [For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very](https://www.python.org/dev/peps/pep-0008) readable and eye-pleasing coding style.
Every Python developer should read it at some point; here are the most important points extracted for you: - Use 4-space indentation, and no tabs. 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read).
Tabs introduce confusion, and are best left out. - Wrap lines so that they don’t exceed 79 characters. This helps users with small displays and makes it possible to have several code files side-by-side on larger displays. - Use blank lines to separate functions and classes, and larger blocks of code inside funct...
Always use self as the name for the first ``` method argument (see A First Look at Classes for more on classes and methods). - Don’t use fancy encodings if your code is meant to be used in international environments.
Python’s default, UTF-8, or even plain ASCII work best in any case. - Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code. ----- ----- **CHAPTER** ### FIVE DATA STRUCTURES This chapter describes some...
Here are all of the methods of list objects: ``` list.append(x) ``` Add an item to the end of the list.
Equivalent to a[len(a):] = [x]. ``` list.extend(iterable) ``` Extend the list by appending all the items from the iterable.
Equivalent to a[len(a):] = iterable. ``` list.insert(i, x) ``` Insert an item at a given position.
The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to ``` a.append(x). list.remove(x) ``` Remove the first item from the list whose value is equal to x.
It raises a ValueError if there is no such item. `list.pop([i` ]) Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list.
(The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position.
You will see this notation frequently in the Python Library Reference.) ``` list.clear() ``` Remove all items from the list.
Equivalent to del a[:]. `list.index(x[, start[, end` ]]) Return zero-based index in the list of the first item whose value is equal to x.
Raises a ValueError if there is no such item. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list.
The returned index is computed relative to the beginning of the full sequence rather than the start argument. ``` list.count(x) ``` Return the number of times x appears in the list. ``` list.sort(key=None, reverse=False) ``` Sort the items of the list in place (the arguments can be used for sort customization, see so...
Equivalent to a[:]. An example that uses most of the list methods: ``` >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> frui...
To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
For example: ``` >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] ``` 1 Other languages may return the mutated object, which allows method chaining, such as ``` d->insert("a")->remove("b...
While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one). To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
For example: ``` >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Rem...
Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. For example, assume we want to create a list of squares, like: ``` >>> squares = [] >>> fo...
squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ``` Note that this creates (or overwrites) a variable named x that still exists after the loop completes.
We can calculate the list of squares without any side effects using: ``` squares = list(map(lambda x: x**2, range(10))) ``` or, equivalently: ``` squares = [x**2 for x in range(10)] ``` which is more concise and readable. A list comprehension consists of brackets containing an expression followed by a for clause, th...
The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not equal: ``` >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ``` and it’s equivalent to: ----- Note how the order of the for and if statements is the same in both these snipp...
the (x, y) in the previous example), it must be parenthesized. ``` >>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>...
[1, 2, 3, 4], ... [5, 6, 7, 8], ``` (continues on next page) ----- (continued from previous page) ``` ... [9, 10, 11, 12], ...
] ``` The following list comprehension will transpose rows and columns: ``` >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalen...
transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` which, in turn, is the same as: ``` >>> transposed = [] >>> for i in range(4): ...
# the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ...
transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` In the real world, you should prefer built-in functions to complex flow statements.
The zip() function would do a great job for this use case: ``` >>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] ``` See Unpacking Argument Lists for details on the asterisk in this line. ### 5.2 The del statement There is a way to remove an item from a list given its index instead of its value:...
This differs from the pop() method which returns a value.
The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice).
For example: ``` >>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] ``` (continues on next page) ----- (continued from previous page) ``` >>> a [] del can also be used to delete entire variables: >>> del a ``` Referencing th...
We’ll find other uses for del later. ### 5.3 Tuples and Sequences We saw that lists and strings have many common properties, such as indexing and slicing operations.
They are two examples of sequence data types (see typesseq). Since Python is an evolving language, other sequence data types may be added.
There is also another standard sequence data type: the tuple. A tuple consists of a number of values separated by commas, for instance: ``` >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ...
u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: ...
t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: ...
v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1]) ``` As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expr...
It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists. Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneo...
Lists are _mutable, and their elements are usually homogeneous and are accessed by iterating over the list._ A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these.
Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
For example: ``` >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) ``` (continues on next page) ----- (continued from previous page) ``` 0 >>> len(singleton) 1 >>> singleton ('hello',) ``` The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 5432...
The reverse operation is also possible: >>> x, y, z = t ``` This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.
Note that multiple assignment is really just a combination of tuple packing and sequence unpacking. ### 5.4 Sets Python also includes a data type for sets.
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries.
Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. Curly braces or the set() function can be used to create sets.
Note: to create an empty set you have to use ``` set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section. ``` Here is a brief demonstration: ``` >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been r...
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”.
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.
You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like ``` append() and extend(). ``` It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
A pair of braces creates an empty dictionary: {}.
Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output. The main operations on a dictionary are storing a value with some key and extracting the value given the key.
It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten.
It is an error to extract a value using a non-existent key. Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead).
To check whether a single key is in the dictionary, use the in keyword. Here is a small example using a dictionary: ``` >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'jack': 4098, 'sape': 4139, 'guido': 4127} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'jack': 4098...
print(k, v) ... gallahad the pure robin the brave ``` When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function. ``` >>> for i, v in enumerate(['tic', 'tac', 'toe']): ...
print(i, v) ... 0 tic 1 tac 2 toe ``` To loop over two or more sequences at the same time, the entries can be paired with the zip() function. ``` >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ...
print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color?
It is blue. ``` To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the ``` reversed() function. >>> for i in reversed(range(1, 10, 2)): ...
print(i) ... 9 7 5 3 1 ``` To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered. ----- It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead. ``` >>...
if not math.isnan(value): ...
filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8] ### 5.7 More on Conditions ``` The conditions used in while and if statements can contain any operators, not just comparisons. The comparison operators in and not in check whether a value occurs (does not occur) in a sequence.
The operators is and is not compare whether two objects are really the same object; this only matters for mutable objects like lists.
All comparison operators have the same priority, which is lower than that of all numerical operators. Comparisons can be chained.
For example, a < b == c tests whether a is less than b and moreover b equals ``` c. ``` Comparisons may be combined using the Boolean operators and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not.
These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C.