A challenge in software development is to keep things simple π€―
For your code to not grow overly complex over time π±
Simple is better than complex.
Zen of Python π
Complex is better than complicated.
Simplicity in your code means fewer possibilities for bugs to hide and easier debugging when they do arise π
It also makes your code more understandable and maintainable, which is crucial in a team setting or when returning to your code after a period of time.
Photo byΒ Pablo ArroyoΒ onΒ Unsplash
Let’s look at 5 examples:
1. Are all numbers divisible?
A good first example is underutilizing the Python built-in functions.
Given you go from supporting checking if one number is divisible:
def is_divisible(num, divisor):
return num % divisor == 0
To multiple numbers:
def is_divisible_by_all(num, divisors):
for divisor in divisors:
if num % divisor != 0:
return False
return True
This is valid and works, but you might write this in a simpler matter using the all() built-in function:
def is_divisible_by_all(num, divisors):
return all(num % divisor == 0 for divisor in divisors)
Very clean / easy to read ππ
2. Dictionary lookups
Another example is doing dictionary lookups, checking if the key is in the dictionary:
Complex (unnecessary):
def get_value(dictionary, key):
if key in dictionary:
return dictionary[key]
else:
return "Key not found"
Better: leverage the fact that Python dicts have a get()
method:
dictionary.get(key, "Key not found")
3. List comprehensions
Say we want to find all even numbers from a list. One approach is to loop through the list, building up a new result list:
def find_even_numbers(numbers):
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
return even_numbers
But what about using a list comprehension?
def find_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
Here, a list comprehension (“listcomp”) offers a more concise and readable alternative to the loop-based approach for this specific task.
4. Unique values
A common task might be to determine if all the items in a list are distinct. One way to do this:
def all_unique(items):
seen = set()
for item in items:
if item in seen:
return False
seen.add(item)
return True
However leveraging sets you can actually write this simpler like this:
def all_unique(items):
return len(items) == len(set(items))
5. Counting things
Lastly, suppose you want to count how many times each word appears in a sentence.
def count_words_verbose(sentence):
word_counts = {}
words = sentence.lower().split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts
Using Counter
here is much more concise and Pythonic:
from collections import Counter
def count_words_refactored(sentence):
return Counter(sentence.lower().split())
Counter
is designed precisely for tasks like this, so it’s not just simpler code, it’s likely more performant as well (in some cases though, more concise code might not be the most optimized in terms of runtime or memory, but it’s often more readable which saves developer time! π‘)
Conclusion
The essence of Python lies not just in its versatility but also in its ethos of simplicity and readability.
As developers, we’re often tempted to craft intricate solutions, believing complexity equates to sophistication.
Yet, as showcased in the examples above, the true art of programming often lies in distilling problems to their core and solving them in the most straightforward manner π‘
Embracing Python’s built-ins and idioms allows us to write not only concise but also effective code.
As you embark on your coding journey, always remember the mantra: “Simple is better than complex.” π
By adhering to this philosophy, you not only make your code more maintainable and bug-resistant but also ensure that it remains a joy to write and read π
Code more idiomatically with our collection of 400 Python exercises on our platform π