Skip to content

Idiomatic Python

ghost edited this page Jan 9, 2021 · 1 revision

Iterating over \*\*args

>>> def call_me(**args):
...     for k, v in args.items():
...             print(k)
...             print(v)
...
>>> call_me(name="Frank")
name
Frank

Grouping with dictionaries

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> names = ["paco", "pao", "xime"]
>>> for name in names:
...     key = len(name)
...     d[key].append(name)
...
>>> d
defaultdict(<class 'list'>, {4: ['paco', 'xime'], 3: ['pao']})

Clarify multuple returns values with namedtuple

>>> from collections import namedtuple
>>> TestResults = namedtuple('TestResults', ['failed', 'attemped'])
>>> TestResults(failed=0, attemped=4)
TestResults(failed=0, attemped=4)

Updating multiple state variables

>>> def fibonacci(n):
...     x, y = 0, 1
...     for i in range(n):
...             print(x)
...             x, y = y, x+y
...
>>> fibonacci(10)
0
1
1
2
3
5
8
13
21
34

Unpacking sequences

>>> name = "pao", "xime", "me"
>>> pao, xime, me = name
>>> pao
'pao'

>>> name = ("pao", "xime", "me")
>>> pao, xime, me = name
>>> me
'me'

>>> name = ["pao", "xime", "paco"]
>>> pao, xime, me = name
>>> me
'paco'