Python tips

O(1) vs O(N) dictionary `in` search.

I recently came across this and it made a huge difference in some of my programs. I figured the issue was just because I was a noob, but I found it (via a grep search) in tons of other production codes.If you're interested in seeing if a dictionary, mydict has the key, 'mykey', the following is O(N): if 'mykey' in mydict.keys(): # do stuffwhile the following is O(1): if 'mykey' in mydict: # do stuffThis is because the dictionary will use a hash-lookup with the latter (like searching a set) while the former will first generate a list and then iterate over it for the in statement (so it may scale as 2N but that is still O(N)).By the way, these are based on average case. See Time Complexity for more detail.

Simplify if-statements with if x in list instead of checking each item separately

Let's say we have a list with main colors red, green, and blue. And somewhere in our code we have a new variable that contains some color, so here c = red. Then we want to check if this is a color from our main colors. We could of course check this against each item in our list like so:

colors = ["red", "green", "blue"]

c = "red"

# cumbersome and error-prone
if c == "red" or c == "green" or c == "blue":
    print("is main color")

But this can become very cumbersome, and we can easily make mistakes, for example if we have a typo here for red. Much simpler and much better is just to use the syntax if x in list:

colors = ["red", "green", "blue"]

c = "red"

# better:
if c in colors:
    print("is main color")

Merge dictionaries with the double asterisk syntax ** (Python 3.5+)

This syntax is new since Python 3.5. If we have two dictionaries and want to merge them, we can use curly braces and double asterisks for both dictionaries. So here dictionary 1 has a name and an age, and dictionary 2 also has the name and then the city. After merging with this concise syntax our final dictionary has all 3 keys in it.

d1 = {'name': 'Alex', 'age': 25}
d2 = {'name': 'Alex', 'city': 'New York'}
merged_dict = {**d1, **d2}
print(merged_dict) # {'name': 'Alex', 'age': 25, 'city': 'New York'}

Concatenate Strings with .join()

Let's say we have a list with different strings, and we want to combine all elements to one string, separated by a space between each word. The bad way is to do it like this:

list_of_strings = ["Hello", "my", "friend"]

# BAD:
my_string = ""
for i in list_of_strings:
    my_string += i + " " 

We defined an empty string, then iterated over the list, and then appended the word and a space to the string. As you should know, a string is an immutable element, so here we have to create new strings each time. This code can be very slow for large lists, so you should immediately forget this approach! Much better, much faster, and also much more concise is to the .join() method:

list_of_strings = ["Hello", "my", "friend"]
my_string = " ".join(list_of_strings)

This combines all the elements into one string and uses the string in the beginning as a separator. So here we use a string with only a space. If we were for example to use a comma here, then the final string has a comma between each word. This syntax is the recommended way to combine a list of strings into one string.