Efficient, pythonic code nicely packaged for consumption.

Python and many of its packages have incredible official documentation, but it can be hard to get through it. Meet Python Quick Tips! For elegant, generalizable solutions to data science problems, see Python Deep Tips (forthcoming).

Why take my word on it?
Don’t. Explore for yourself. Each tip has links to documentation and each block of code runs in a Jupyter Notebook.

Python Resources

Python Core

# Best. Plan ahead.  
members_set = {1, 2, 3, 4, 1, 2}
print(0 in members_set)
# => False
# Slow, but best you can do if only testing once and must use a list
# due to other constraints.
members_list = [1, 2, 3, 4, 1, 2]
print(0 in members_list)
# => False
# Better, but only pays off if doing membership testing multiple
# times.
members_from_cast = set(members_list)
other_list = ['a', 'b', 'c']
for other in other_list:
print(other in members_from_cast)
# => False
# => False
# => False

2. Use dictionary comprehensions and set comprehensions.
Dictionary and set comprehensions offer the same readability, compact representation and speed advantages that list comprehensions do.

prime_numbers = [2, 3, 5, 7, 11, 13] 

# Less compact.
primes_squared = {}
for prime_number in prime_numbers:
primes_squared.update({prime_number: prime_number**2})
print(primes_squared)
# => {2: 4, 3: 9, 5: 25, 7: 49, 11: 121, 13: 169}
# Compact, faster, pythonic.
primes_better = {x : x**2 for x in prime_numbers}
print(primes_better)
# => {2: 4, 3: 9, 5: 25, 7: 49, 11: 121, 13: 169}
# Less compact.
primes_squared_set = set({})
for prime_number in prime_numbers:
primes_squared_set.add(prime_number**2)
print(primes_squared_set)
# => {4, 9, 169, 49, 121, 25}
# Compact, faster, pythonic.
primes_better_set = {x**2 for x in prime_numbers}
print(primes_better_set)
# => {4, 9, 169, 49, 121, 25}

This article gets updated whenever I think something is worthy. Check back for updates. Last updated: 3 March 2021.

Mathematician, enjoys his knowledge distilled. Find my insight deep, my jokes laughable, my resources useful, connect with me on twitter @Rowlando_13