VOOZH about

URL: https://dev.to/leechon/python-power-moves-5-tricks-to-level-up-your-code-today-4l00

โ‡ฑ ๐Ÿ Python Power Moves: 5 Tricks to Level Up Your Code Today - DEV Community


Python is famous for its readability, but thereโ€™s a big gap between โ€œworking codeโ€ and โ€œelegant, efficient code.โ€ Whether you're a beginner or a seasoned developer, these five practical tricks will help you write cleaner, faster, and more Pythonic code.


๐Ÿš€ 1. Leverage List Comprehensions for Speed and Clarity

The Problem: You often write loops to create lists, which is verbose and slower.

The Trick: Use list comprehensions โ€“ theyโ€™re more concise and run faster because they avoid append overhead.

# BAD
squares = []
for i in range(10):
 squares.append(i**2)

# GOOD
squares = [i**2 for i in range(10)]

Pro Tip: You can add conditionals:

even_squares = [i**2 for i in range(20) if i % 2 == 0]

Benchmark: List comprehensions are roughly 2x faster than equivalent for-loops in CPython.


๐Ÿงฐ 2. Use enumerate and zip Like a Pro

The Problem: You need to loop over a list with index, or combine multiple lists.

The Trick: enumerate gives you (index, value) tuples; zip pairs iterables easily.

# Instead of:
for i in range(len(items)):
 print(i, items[i])

# Do:
for i, item in enumerate(items):
 print(i, item)

# Combining lists:
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 87, 92]
for name, score in zip(names, scores):
 print(f"{name}: {score}")

Bonus: enumerate accepts a start parameter. Great for numbering output starting from 1.


โšก 3. Master Context Managers with with

The Problem: You manually open and close files, or handle resources, risking leaks.

The Trick: Use with statements that automatically call __enter__ and __exit__.

# Without context manager
file = open('data.txt', 'r')
data = file.read()
file.close() # Don't forget!

# With context manager
with open('data.txt', 'r') as file:
 data = file.read()
# Automatically closed even if exception occurs

Custom Context Manager: Use contextlib.contextmanager for simple cases:

from contextlib import contextmanager

@contextmanager
def tag(name):
 print(f"<{name}>")
 yield
 print(f"</{name}>")

with tag('h1'):
 print('Hello, World!')
# Output: <h1> Hello, World! </h1>

๐ŸŽฏ 4. Write Readable Code with Structural Pattern Matching (Python 3.10+)

The Problem: Long if-elif chains are hard to maintain and read.

The Trick: Use match-case for pattern matching, inspired by functional languages.

def handle_command(command):
 match command.split():
 case ['quit']:
 print('Goodbye!')
 sys.exit(0)
 case ['hello', name]:
 print(f'Hello, {name}!')
 case _:
 print('Unknown command')

Advanced: Match on data structures:

def process_point(point):
 match point:
 case (0, 0):
 print('Origin')
 case (x, 0):
 print(f'On X-axis at {x}')
 case (0, y):
 print(f'On Y-axis at {y}')
 case (x, y):
 print(f'At ({x}, {y})')

This replaces tedious if isinstance() checks.


๐Ÿ”ฎ 5. Use __slots__ to Save Memory in Classes

The Problem: Python classes store attributes in an underlying dictionary (dict) consuming extra memory.

The Trick: Define __slots__ to tell Python exactly which attributes the class has. This eliminates dict, reducing memory usage by 40-60% per instance.

# Without slots
class Point:
 def __init__(self, x, y):
 self.x = x
 self.y = y

# With slots
class Point:
 __slots__ = ('x', 'y')
 def __init__(self, x, y):
 self.x = x
 self.y = y

Caveats:

  • You cannot add new attributes not listed in __slots__.
  • Inheritance requires care (child must define its own __slots__ or a dict is added).

Benchmark: For a class with 2 attributes, memory per instance drops from ~56 bytes to ~32 bytes.


๐Ÿ“ฆ Putting It All Together

Hereโ€™s a real example combining several tricks:

from sys import getsizeof

class DataPoint:
 __slots__ = ('x', 'y', 'value')
 def __init__(self, x, y, value):
 self.x = x
 self.y = y
 self.value = value

# Load data from file
with open('data.csv') as f:
 lines = f.readlines()[1:] # skip header

# Parse with list comprehension and structural pattern matching
points = []
for line in lines:
 match line.strip().split(','):
 case [x, y, v]:
 points.append(DataPoint(int(x), int(y), float(v)))
 case _:
 print(f'Skipping bad line: {line}')

print(f'Total points: {len(points)}')
print(f'Size of one point: {getsizeof(points[0])} bytes')

โœ… Conclusion

These five tricks can dramatically improve your Python code:

  1. List comprehensions for speed and clarity.
  2. enumerate and zip for clean loops.
  3. Context managers for safe resource handling.
  4. Structural pattern matching for readable conditionals.
  5. __slots__ for memory efficiency.

Your Turn: Pick one trick you haven't used before and refactor an existing script. You'll be amazed at the difference!

If you found this helpful, follow me for more Python tips and tutorials. Drop a comment with your favorite Python trick โ€“ Iโ€™d love to learn from you too! ๐Ÿโœจ


๐Ÿ”ง Want free AI tools? Check out AI Toolbox โ€” text improver, translator, code generator, and more. No signup needed.