Python Flashcards
Iterable protocol
iterables (implementing __iter__() )
iterators (implementing __next__() )
can be used in
for [var] in [iterable].
Functionaly equivalent to: obj = train.\_\_iter\_\_() name = obj.\_\_next\_\_() do something with name name = obj.\_\_next\_\_() do something with name ... until IndexError is raised (?)
‘with’ protocol
__enter__()
__exit__()
Dictionary comprehension on prev dict
new_dict = {key:value for (key,value) in old_dict.items()} new_dict = {key:value for (key,value) in old_dict.items()}
Dictionary comprehension from scratch
{n:n**2 for n in numbers if n%2 == 0}
Dictionary comprehension conditional val
{k:(‘even’ if v%2==0 else ‘odd’) for (k,v) in dict1.items()}
Dictionary creation
dict_var = {key1:val1, key2:val2}
Set creation
set_var = {val1, val2}
List creation
list_var = [ val1, val2 ]
Set comprehension
{s**2 for s in range(10)}
List comprehension
[s**2 for s in range(10)]
Lists vs Tuples
lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.
__name__ contents
“__main__” - if you run this script,
filename - if you import the script as a module.
Override comparison
>>> class Whateva: ... def \_\_eq\_\_(self, other): ... return True
REPL
== Interpreter.
Read, Evaluate, Print, Repeat.
Equality vs Identity
'==' vs 'is' contents equal (and overridable) , vs references the same object (non overridable)