Search notes:

Python: sequence

An object that implements the two methods __getitem__() and __len__() is a sequence.
The number of elements that a sequence stores is returned by the builtin function len()
A sequence is a special kind of an iterable.
Some built-in sequence types include
Although dict also implements __getitem__ and __len__, it is considered to be mapping rather than an sequence because the elements a dict contains are looked up with immutable keys rather than just integers.

Evaluating an expression on each element in a sequence

In order to evaluate an expression on each element of a sequence, a so-called list comprehension can be used.

Indexing elements of sequences

numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']

print(numbers[4])
#
# four

print(numbers[2:5])
#
# ['two', 'three', 'four']

print(numbers[-2])
#
# five

print(numbers[-3:-1])
#
# ['four', 'five']

print(numbers[-3:])
#
# ['four', 'five', 'six']

print(numbers[5:])
#
# ['five', 'six']

print(numbers[1:6:2])
#
# ['one', 'three', 'five']

print(numbers[:])
#
# ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
Github repository about-Python, path: /iterable/sequence/indexing.py

Sequence unpacking

Sequence unpacking assigns the value of each element in a sequence to a variable.
seq = ['A', 2, 'three']

x, y, z = seq

print(x)  #  A
print(y)  #  2
print(z)  #  three
Github repository about-Python, path: /iterable/sequence/unpacking.py
The number of variables must correspond to the number of elements in the sequence, otherwise, the Python interpreter raises either a ValueError exception with the explanatory message too many values to unpack or not enough values to unpack.
Note, the var_1, var_2, var_3, … syntax is also used for creating tuples.
The pattern syntax of Structural Pattern Matching builds on sequence unpacking.
TODO: Apparently, the more correct term for this feature is iterable unpacking.

Index