0 - Loop over a range of numbers
Use range
instead of xrange
. In python3, the former creates an iterator that produces the values one at a time making it much more efficient and fast.
=
print
1 - Looping backwards
.reversed use Just
=
print
2 - Looping over a list and its indices
To keep track of the index of each item in a collection, enumerate is your buddy.
=
print ,
3 - Looping over two lists simultaneously
Yeah you could use zip, but izip is faster, so use that instead.
=
=
print ,
4 - Looping over a sorted list
You can sort out the list first and then loop through it, or you could use sorted.
=
print
And BAM, you're ... sorted.
5 - Call a function until a sentinel value is returned
To do that, use iter().
Bad example:
Loop over a file containing a list of names until the loop returns an empty string, in which case we break out of it.
=
=
break
Beautiful example:
In this case, we call a function (f.read) until it returns the sentinel value passed as a second argument to iter. That way we avoid having to make the unnecessary if check.
print
6 - Looping over a dictionary
The normal way to do it:
=
print
If you wish to mutate the data, prefer dict.keys()
.
=
# do the mutation
7 - Looping over a dict keys AND values
Don't do this:
=
print
It's slow because we have to rehash the dictionary and do a lookup everytime.
Instead choose iteritems()
:
=
print ,
8 - Create a dict out of two lists
Just instantiate a new dict with two zipped lists. Real magic.
=
=
=
9 - Use named tuples for returning multiple values
Like in the case of an API response in Flask.
=
:
=
return
Other
- Always clarify function calls by using keyword arguments
If you learned something from this article, share it with your co-workers and fellow hackers. If you notice any typo, error etc let me know on twitter.