Skip to content

PythonHintsForNoobs

Anthony Sottile edited this page Aug 18, 2020 · 4 revisions

Data types

  • dict (python<3.6) and set are unordered types, This means iterating them, their keys, or their values is not well defined
  • list and tuple are ordered types. Iterating them is well defined
  • tuple is immutable, it cannot be modified. If you want a mutable thing, use a list or deque

Useless branches

derpy

if foo == 'bar':
    return True
else:
    return False
return True if foo == 'bar' else False

not derpy

return foo == 'bar'

builtin types make a shallow copy on construction

dict(...).copy() is a redundant shallow copy, write dict(...) instead

Iterating a dict gives you its keys

derpy

[f(x) for x in dct.keys()]
y in dct.keys()
set(dct.keys())

not derpy

[f(x) for x in dct]
y in dct
set(dct)
Clone this wiki locally