Using list and dict comprehension is simpler and computationally quicker than calling list()
and dict()
.
Comprehensions are more efficient than calling dict()
and list()
.
Given that these are completely equivalent:
Why not choose the easiest to both read, write, and quickest to execute (the first one)?
Do not follow this advice with set comprehension though, as when set comprehension is performed on an empty iterable it returns a dict
because Python cannot differentiate set comprehension and dict comprehension when working with an empty iterable:
Notice that four
evaluated to an empty dict, which was unwanted behaviour.
If our GitHub code review bot spots this issue in your pull request it gives this advice:
1 | + | dict((item, get_value(item)) for item in items) |
Using list and dict comprehension is simpler and computationally quicker than calling list()
and dict()
.
- | dict((item, get_value(item)) for item in items) |
+ | {item: get_value(item) item item in items} |