Container sequences: can hold different types. They contain references to the objects.
list, tuple, collections.deque
Flat sequences: can hold one type. They physically sotre the value.
str, bytes, bytearray, memoryview, array.array
Another way of grouping:
Mutable seuqences:
list, byte, array.array, collections.deque and memoryview
Immutable sequences:
tuple, str, bytes
List Comprehensions and Generator Expressions
Readability
List comprehension is meant to do one thing only: to build a new list. It is possible to abuse it to write very incomprehensible code, you should avoid it.
symbols = '$¢£¥€¤' codes = [ord(symbol) for symbol in symbols] codes
[36, 162, 163, 165, 8364, 164]
No leak in Python 3
x = 'ABC' dummy = [ord(x) for x in x] x
ABC
dummy
[65, 66, 67]
Versus map and filter
beyond_ascii = [ord(s) for s in symbols if ord(s) > 127] beyond_ascii
[162, 163, 165, 8364, 164]
beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols))) beyond_ascii
[162, 163, 165, 8364, 164]
Cartesian Products
Multiple Loops
colors = ['black', 'white'] sizes = ['S', 'M', 'L'] tshirts = [(color, size) for color in colors for size in sizes] tshirts
for name, cc, pop, (latitude, longitude) in metro_areas: if longitude <= 0: print(fmt.format(name, latitude, longitude))
| lat. | long.
Mexico City | 19.4333 | -99.1333
New York-Newark | 40.8086 | -74.0204
Sao Paulo | -23.5478 | -46.6358
Named Tuples
from collections import namedtuple City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) tokyo