How to Write Comprehensions and Alienate People
Python list comprehensions are a powerful feature that can make code more concise and readable. However, like any powerful tool, they can also be misused to create code that’s virtually incomprehensible. Here’s a guide to writing comprehensions that will make your colleagues wonder if you’re actually writing Python or inventing a new language.
The Basics of Alienation
Start with simple list comprehensions:
# Instead of this clear code:
squares = []
for i in range(10):
squares.append(i * i)
# Write this one-liner:
squares = [i * i for i in range(10)]
But that’s too readable! Let’s make it more interesting.
Advanced Techniques
Nested Comprehensions
Why use one comprehension when you can nest three?
# Instead of nested loops:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
flattened = []
for row in matrix:
for num in row:
if num % 2 == 0:
flattened.append(num * 2)
# Write this beauty:
flattened = [num * 2 for row in matrix for num in row if num % 2 == 0]
Dictionary Comprehensions
Make your dictionaries unreadable too:
# Instead of:
word_lengths = {}
for word in words:
if len(word) > 3:
word_lengths[word] = len(word)
# Write:
word_lengths = {word: len(word) for word in words if len(word) > 3}
Expert-Level Techniques
The Triple Threat
Combine list, dictionary, and set comprehensions:
# This monstrosity:
result = {
key: [set(x for x in value if x.isalpha())
for value in values if len(value) > 2]
for key, values in data.items()
if key.startswith('important_')
}
Generator Expressions
For when you want to confuse people about memory usage:
# Instead of a simple list:
numbers = (x for x in range(1000000) if x % 3 == 0 and x % 5 == 0)
Best Practices for Maximum Confusion
- Never break long comprehensions into multiple lines
- Always nest at least three levels deep
- Include complex lambda functions
- Mix multiple types of comprehensions
- Use cryptic variable names like ‘x’, ‘y’, and ‘z’
When to Use These Techniques
- Code reviews where you want to assert dominance
- Open source projects you never want anyone to contribute to
- Job security through obscurity
- Winning “most creative” in your team’s code golf tournament
Conclusion
Remember, with great power comes great responsibility to make your code as complex as possible. While Python comprehensions were designed to make code more readable, with these techniques, you can ensure that no one will ever want to maintain your code again.
Disclaimer: This is satire. Please write readable code. Your future self (and colleagues) will thank you.