This chapter describes some stuff you’ve realized about already in more ingredient,
and adds some recent things as neatly.

5.1. More on Lists

The checklist files style has some more options. Listed below are all of the options of checklist


Add an item to the cease of the checklist. The same to a[len(a):] = [x].


Lengthen the checklist by appending the total objects from the iterable. The same to
a[len(a):] = iterable.

checklist.insert(i, x)

Insert an item at a given remark. The vital argument is the index of the
ingredient before which to insert, so a.insert(0, x) inserts on the front of
the checklist, and a.insert(len(a), x) is comparable to a.append(x).


Have the first item from the checklist whose price is equal to x. It raises a
ValueError if there is not any such thing as a such item.


Have the object on the given remark in the checklist, and return it. If no index
is specified, a.pop() will get rid of and returns the closing item in the checklist. (The
square brackets throughout the i in the trend signature denote that the parameter
is no longer mandatory, no longer that it’s essential always style square brackets at that remark. You
will peek this notation veritably in the Python Library Reference.)


Have all objects from the checklist. The same to del a[:].

checklist.index(x[, start[, end]])

Return zero-primarily primarily based index in the checklist of the first item whose price is equal to x.
Raises a ValueError if there is not any such thing as a such item.

The no longer mandatory arguments initiate and cease are interpreted as in the cleave
notation and are light to restrict the search to a particular subsequence of
the checklist. The returned index is computed relative to the starting up of the beefy
sequence reasonably than the initiate argument.


Return the quantity of times x seems in the checklist., reverse=Misguided)

Kind the objects of the checklist in remark (the arguments can even be light for style
customization, peek sorted() for his or her clarification).


Reverse the parts of the checklist in remark.


Return a shallow reproduction of the checklist. The same to a[:].

An example that makes exhaust of heaps of the checklist options:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
>>> fruits.count('tangerine')
>>> fruits.index('banana')
>>> fruits.index('banana', 4)  # Receive next banana starting a remark 4
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()

That you might need seen that options be pleased insert, salvage or style that
most efficient regulate the checklist haven’t any return price printed – they return the default
None. 1 Right here’s a originate theory for all mutable files constructions in

One other reveal you will be succesful of be taught is that no longer all files can even be sorted or
when in contrast. To illustrate, [None, 'hello', 10] doesn’t style because
integers can’t be when in contrast to strings and None can’t be when in contrast to
assorted kinds. Additionally, there are some kinds that don’t safe a defined
ordering relation. As an illustration, 3+4j < 5+7j isn’t a valid

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved (“last-in, first-out”). 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()
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
>>> stack.pop()
>>> stack
[3, 4]

5.1.2. The exhaust of Lists as Queues

It is furthermore possible to exhaust a checklist as a queue, the place the first ingredient added is
the first ingredient retrieved (“first-in, first-out”); nonetheless, lists are no longer
atmosphere excellent for this motive. While appends and pops from the cease of checklist are
swiftly, doing inserts or pops from the starting up of a checklist is unhurried (because all
of the assorted parts need to be shifted by one).

To implement a queue, exhaust collections.deque which used to be designed to
safe swiftly appends and pops from every ends. As an illustration:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The vital to arrive now leaves
>>> queue.popleft()                 # The 2d to arrive now leaves
>>> queue                           # Remaining queue in expose of arrival
deque(['Michael', 'Terry', 'Graham'])

5.1.3. Checklist Comprehensions

Checklist comprehensions present a concise formula to originate lists.
Total applications are to discover recent lists the place every ingredient is the results of
some operations utilized to every member of some other sequence or iterable, or to
originate a subsequence of these parts that fulfill a obvious situation.

As an illustration, make a selection we want to originate a checklist of squares, be pleased:

>>> squares = []
>>> for x in vary(10): 
...     squares.append(x2)
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Demonstrate that this creates (or overwrites) a variable named x that also exists
after the loop completes. We can calculate the checklist of squares with none
facet results the utilization of:

squares = checklist(draw(lambda x:  x2, vary(10)))

or, equivalently:

squares = [x2 for x in range(10)]

which is more concise and readable.

A checklist comprehension includes brackets containing an expression followed
by a for clause, then zero or more for or if
clauses. The tip result will be a recent checklist attributable to evaluating the expression
in the context of the for and if clauses which note it.
As an illustration, this listcomp combines the parts of two lists if they’re no longer

>>> [(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 comparable to:

>>> combs = []
>>> for x in [1,2,3]: 
...     for y in [3,1,4]: 
...         if x != y: 
...             combs.append((x, y))
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Demonstrate how the expose of the for and if statements is the
identical in every these snippets.

If the expression is a tuple (e.g. the (x, y) in the old example),
it will likely be parenthesized.

>>> vec = [-4, -2, 0, 2, 4]
>>> # originate a recent checklist with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the checklist to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # note a fair to the total parts
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a formula on every ingredient
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # originate a checklist of 2-tuples be pleased (quantity, square)
>>> [(x, x2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple need to be parenthesized, otherwise an error is raised
>>> [x, x2 for x in range(6)]
  File "", line 1, in 
    [x, x2 for x in range(6)]
SyntaxError: invalid syntax
>>> # flatten a checklist the utilization of a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Checklist comprehensions can possess advanced expressions and nested functions:

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4. Nested Checklist Comprehensions

The preliminary expression in a checklist comprehension can even be any arbitrary expression,
alongside with some other checklist comprehension.

Accumulate into legend the next example of a 3×4 matrix implemented as a checklist of
3 lists of length 4:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The next checklist comprehension will transpose rows and columns:

>>> [[row[i] for row in matrix] for i in vary(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the old half, the nested listcomp is evaluated in
the context of the for that follows it, so this case is
comparable to:

>>> transposed = []
>>> for i in vary(4): 
...     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 identical as:

>>> transposed = []
>>> for i in vary(4): 
...     # the next 3 traces 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 particular world, it’s essential always salvage constructed-in functions to advanced stride alongside with the circulation statements.
The zip() fair would impact a immense job for this exhaust case:

>>> checklist(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

Seek Unpacking Argument Lists for well-known points on the asterisk on this line.

5.2. The del narrate

There could be a formula to salvage an item from a checklist given its index reasonably than its
price: the del narrate. This differs from the pop() formula
which returns a price. The del narrate can furthermore be light to salvage
slices from a checklist or sure your total checklist (which we did earlier by project
of an empty checklist to the cleave). As an illustration:

>>> 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[:]
>>> a

del can furthermore be light to delete total variables:

Referencing the title a hereafter is an error (a minimum of till some other price
is assigned to it). We’ll salvage assorted makes exhaust of for del later.

5.3. Tuples and Sequences

We saw that lists and strings safe many customary properties, such as indexing and
slicing operations. They’re two examples of sequence files kinds (peek
Sequence Kinds — checklist, tuple, vary). Since Python is an evolving language, assorted sequence files
kinds will be added. There might be furthermore some other weird and wonderful sequence files style: the

A tuple includes heaps of values separated by commas, for instance:

>>> t = 12345, 54321, 'hiya!'
>>> t[0]
>>> t
(12345, 54321, 'hiya!')
>>> # Tuples will be nested: 
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hiya!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable: 
... t[0] = 88888
Traceback (most most modern call closing): 
  File "", line 1, in 
TypeError: 'tuple' object doesn't toughen item project
>>> # nonetheless they'll possess mutable objects: 
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

As you peek, on output tuples are continuously enclosed in parentheses, so that nested
tuples are interpreted appropriately; they’ll be enter with or without surrounding
parentheses, though every so often parentheses are needed anyway (if the tuple is
half of a increased expression). It is no longer possible to build to the particular person
objects of a tuple, nonetheless it’s miles possible to originate tuples which possess mutable
objects, such as lists.

Though tuples can also merely seem comparable to lists, they’re every so often light in assorted
scenarios and for assorted applications.
Tuples are immutable, and each so often possess a heterogeneous sequence of
parts which will be accessed by the utilization of unpacking (peek afterward this half) or indexing
(and even by attribute in the case of namedtuples).
Lists are mutable, and their parts are every so often homogeneous and are
accessed by iterating over the checklist.

A special reveal is the building of tuples containing 0 or 1 objects: 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 price with a comma (it is not ample to encompass a single price
in parentheses). Grisly, nonetheless effective. As an illustration:

>>> empty = ()
>>> singleton = 'hiya',    # <-- note trailing comma
>>> len(empty)
>>> len(singleton)
>>> singleton

The narrate t = 12345, 54321, 'hiya!' is an example of tuple packing:
the values 12345, 54321 and 'hiya!' are packed collectively in a tuple.
The reverse operation is furthermore possible:

Right here’s known as, appropriately ample, sequence unpacking and works for any
sequence on the coolest-hand facet. Sequence unpacking requires that there are as
many variables on the left facet of the equals tag as there are parts in the
sequence. Demonstrate that more than one project is indubitably correct a combination of tuple
packing and sequence unpacking.

5.4. Sets

Python furthermore entails a files style for objects. A field is an unordered series
and not using a reproduction parts. Total makes exhaust of encompass membership testing and
taking out reproduction entries. Position objects furthermore toughen mathematical operations
be pleased union, intersection, distinction, and symmetric distinction.

Curly braces or the field() fair can even be light to originate objects. Demonstrate: to
originate an empty field you will be succesful of must exhaust field(), no longer {}; the latter creates an
empty dictionary, a files structure that we discuss in the next half.

Right here is a brief demonstration:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # tag that duplicates were eliminated
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # swiftly membership testing
>>> 'crabgrass' in basket

>>> # Blow their non-public horns field operations on unique letters from two phrases
>>> a = field('abracadabra')
>>> b = field('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a nonetheless no longer in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or every
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in every a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b nonetheless no longer every
{'r', 'd', 'b', 'm', 'z', 'l'}

Equally to checklist comprehensions, field comprehensions
are furthermore supported:

>>> a = {x for x in 'abracadabra' if x no longer in 'abc'}
>>> a
{'r', 'd'}

5.5. Dictionaries

One other priceless files style constructed into Python is the dictionary (peek
Mapping Kinds — dict). Dictionaries are every so often chanced on in assorted languages as
“associative recollections” or “associative arrays”. Unlike sequences, which will be
listed by a form of numbers, dictionaries are listed by keys, which will be
any immutable style; strings and numbers can continuously be keys. Tuples can even be light
as keys if they possess most efficient strings, numbers, or tuples; if a tuple includes
any mutable object both at present or no longer at present, it’s miles going to’t be light as a key.
That you might’t exhaust lists as keys, since lists can even be modified in remark the utilization of index
assignments, cleave assignments, or options be pleased append() and

It is most efficient to ponder a dictionary as a field of key: price pairs,
with the requirement that the keys are unique (internal one dictionary). A pair of
braces creates an empty dictionary: {}. Placing a comma-separated checklist of
key:price pairs internal the braces adds preliminary key:price pairs to the
dictionary; this is furthermore the trend dictionaries are written on output.

The vital operations on a dictionary are storing a price with some key and
extracting the price given the important thing. It is furthermore possible to delete a key:price
pair with del. While you retailer the utilization of a key that is already in exhaust, the feeble
price associated with that key is forgotten. It is an error to extract a price
the utilization of a non-existent key.

Performing checklist(d) on a dictionary returns a checklist of the total keys
light in the dictionary, in insertion expose (while you occur to determine it sorted, correct exhaust
sorted(d) as a replacement). To envision whether or no longer a single key is in the
dictionary, exhaust the in key phrase.

Right here is a diminutive example the utilization of a dictionary:

>>> tel = {'jack':  4098, 'sape':  4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> checklist(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
>>> 'jack' no longer in tel

The dict() constructor builds dictionaries at present from sequences of
key-price pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

Apart from, dict comprehensions can even be light to originate dictionaries from
arbitrary key and worth expressions:

>>> {x:  x2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are easy strings, it’s miles every so often simpler to specify pairs the utilization of
key phrase arguments:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

5.6. Looping Methods

When looping by dictionaries, the important thing and corresponding price can even be
retrieved on the identical time the utilization of the objects() formula.

>>> knights = {'gallahad':  'the pure', 'robin':  'the brave'}
>>> for k, v in knights.objects(): 
...     print(k, v)
gallahad the pure
robin the brave

When looping by a chain, the remark index and corresponding price can
be retrieved on the identical time the utilization of the enumerate() fair.

>>> for i, v in enumerate(['tic', 'tac', 'toe']): 
...     print(i, v)
0 tic
1 tac
2 toe

To loop over two or more sequences on the identical time, the entries can even be paired
with the zip() fair.

>>> questions = ['name', 'quest', 'favorite color']
>>> solutions = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, solutions): 
...     print('What is your {0}?  It is {1}.'.format(q, a))
What is your title?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a chain in reverse, first specify the sequence in a forward
direction and then call the reversed() fair.

>>> for i in reversed(vary(1, 10, 2)): 
...     print(i)

To loop over a chain in sorted expose, exhaust the sorted() fair which
returns a recent sorted checklist whereas leaving the provision unaltered.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(field(basket)): 
...     print(f)

It is every so often tempting to substitute a checklist while you are looping over it;
nonetheless, it’s miles every so often more helpful and safer to originate a recent checklist as a replacement.

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for price in raw_data: 
...     if no longer math.isnan(price): 
...         filtered_data.append(price)
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

5.7. More on Conditions

The stipulations light in whereas and if statements can possess any
operators, no longer correct comparisons.

The comparability operators in and no longer in test whether or no longer a price occurs
(doesn’t occur) in a chain. The operators is and is no longer compare
whether or no longer two objects are indubitably the identical object; this most efficient matters for mutable
objects be pleased lists. All comparability operators safe the identical priority, which is
decrease than that of all numerical operators.

Comparisons can even be chained. As an illustration, 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. As always, parentheses
can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined. For example, if A and C are
true but B is false, A and B and C does not evaluate the expression
C. When used as a general value and not as a Boolean, the return value of a
short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression
to a variable. For example,

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null

Demonstrate that in Python, unlike C, project internal expressions need to be carried out
explicitly with the
walrus operator :=.
This avoids a customary class of concerns encountered in C programs: typing =
in an expression when == used to be supposed.

5.8. Comparing Sequences and Other Kinds

Sequence objects every so often will be when in contrast to assorted objects with the identical sequence
style. The comparability makes exhaust of lexicographical ordering: first the first two
objects are when in contrast, and if they vary this determines the consequence of the
comparability; if they’re equal, the next two objects are when in contrast, and plenty of others, till
both sequence is exhausted. If two objects to be when in contrast are themselves
sequences of the identical style, the lexicographical comparability is implemented
recursively. If all objects of two sequences compare equal, the sequences are
regarded as equal. If one sequence is an preliminary sub-sequence of the assorted, the
shorter sequence is the smaller (lesser) one. Lexicographical ordering for
strings makes exhaust of the Unicode code level quantity to expose particular person characters.
Some examples of comparisons between sequences of the identical style:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Demonstrate that comparing objects of assorted kinds with < or > is appropriate
given that the objects safe acceptable comparability options. As an illustration,
mixed numeric kinds are when in contrast primarily primarily based on their numeric price, so 0 equals
0.0, and plenty of others. In every other case, reasonably than offering an arbitrary ordering, the
interpreter will elevate a TypeError exception.