15 Python Tricks Every Beginner Wishes They Knew Earlier

Python Tricks for Beginners - My Code Diary

15 Python Tricks Every Beginner Wishes They Knew Earlier

By My Code Diary


I still remember the day my senior developer looked at my code and said, “This works. But did you know Python can do this in one line?” I nodded confidently. I had no idea what he meant. That one moment sent me down a rabbit hole that took me four years to fully explore.

The truth is, Python is deceptively simple on the surface. You can write code that works, ship it, and never realize you’ve been doing things the slow, painful, unnecessary way. These 15 tricks are not about being clever for the sake of it. Each one solves a real problem, one I personally hit face-first.


1. Swap Variables Without a Temp Variable

Every beginner writes this:

temp = a
a = b
b = temp

Python laughs at this. Here’s what you should write:

a, b = b, a

One line. No temp variable. No confusion. This is called tuple unpacking, and once you see it, you cannot unsee it.


2. Use enumerate() Instead of a Counter Variable

Most beginners track the index manually:

i = 0
for item in my_list:
    print(i, item)
    i += 1

Python has a built-in for exactly this:

for i, item in enumerate(my_list):
    print(i, item)

You can even set the starting index: enumerate(my_list, start=1). Small thing. Big difference.


3. List Comprehensions Are Not Magic, They Are Faster

The first time someone showed me a list comprehension, I thought it was a flex. It is not. It is genuinely faster than a for loop in most cases and far more readable once you get used to it.

# Old way
squares = []
for n in range(10):
    squares.append(n ** 2)

# Better way
squares = [n ** 2 for n in range(10)]

Pro Tip: If your list comprehension runs longer than one line, it’s a sign you should break it into a function instead. Readability always wins.


4. zip() to Loop Over Two Lists at Once

This is one of those tricks that sounds obvious after you learn it, and drives you crazy that nobody told you earlier.

names = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 79]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

No index juggling. No names[i]. Just clean, readable code.


5. Default Dictionary Values with .get()

Every beginner has written something like this and crashed:

value = my_dict["key_that_might_not_exist"]

The fix is embarrassingly simple:

value = my_dict.get("key_that_might_not_exist", "default_value")

The second argument is the fallback. If the key does not exist, you get the default. No KeyError. No try-except block needed.


6. collections. defaultdict for Grouping Data

Let’s say you are grouping a list of names by their first letter. Without defaultdict, you write five lines of setup. With it:

from collections import defaultdict

grouped = defaultdict(list)
names = ["Alice", "Anna", "Bob", "Brian", "Charlie"]

for name in names:
    grouped[name[0]].append(name)

print(dict(grouped))
# {'A': ['Alice', 'Anna'], 'B': ['Bob', 'Brian'], 'C': ['Charlie']}

This saved me hours across dozens of data-processing scripts. It is one of those tools that, once you add it to your toolbox, you use it constantly.


7. f-Strings Are the Only String Formatting You Need

If you are still using .format() or % formatting in 2026, this one is for you.

name = "Sarah"
score = 95.678

# Old
print("Hello %s, your score is %.2f" % (name, score))

# Better
print(f"Hello {name}, your score is {score:.2f}")

f-Strings are faster, cleaner, and support expressions directly inside the braces. You can even do {2 + 2}, and it will print 4. That is not magic. That is just Python.


8. Ternary Expressions for Short Conditions

Stop writing five-line if-else blocks for simple assignments.

# Long way
if age >= 18:
    status = "adult"
else:
    status = "minor"

# Short way
status = "adult" if age >= 18 else "minor"

Use this when the condition is genuinely simple. If it gets complicated, go back to the full if-else. Readability is not negotiable.


9. Unpacking with * for Flexible Assignments

This one is criminally underused. You can unpack the first and last elements while dumping the middle into a separate list.

first, *middle, last = [1, 2, 3, 4, 5]

print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

This is particularly useful when parsing data files where the structure is not perfectly uniform.


10. Use any() and all() Instead of Long Boolean Loops

You have a list. You want to check if any element meets a condition. Do not write a loop.

scores = [45, 60, 72, 88, 55]

# Check if any score is above 80
print(any(s > 80 for s in scores))  # True

# Check if all scores are above 50
print(all(s > 50 for s in scores))  # False

These are built-in functions that return True or False. They are also short-circuit, meaning they stop evaluating the moment they find an answer. Faster and cleaner.


11. Counter for Frequency Counting

How many times have you manually counted occurrences in a list? Once you discover Counter, you will never do it manually again.

from collections import Counter

words = ["python", "java", "python", "c++", "python", "java"]
count = Counter(words)

print(count)
# Counter({'python': 3, 'java': 2, 'c++': 1})

print(count.most_common(2))
# [('python', 3), ('java', 2)]

This one line replaces what used to be a six-line dictionary-building loop for me. It also works on strings, counting individual characters.


12. Context Managers (with Statement) Are Not Just for Files

Most beginners know with open("file.txt") as f:. Fewer know you can write your own context managers for any setup-teardown pattern.

from contextlib import contextmanager
import time

@contextmanager
def timer():
    start = time.time()
    yield
    end = time.time()
    print(f"Elapsed: {end - start:.4f}s")

with timer():
    # your code here
    result = sum(range(1_000_000))

This is how I benchmark every function I write now. No external libraries. Pure Python. Four years in, I still use this every week.


13. Chaining Comparisons Like a Human Would Write Them

Python lets you write comparisons the way you would say them out loud.

# Instead of this
if x > 0 and x < 100:
    pass

# Write this
if 0 < x < 100:
    pass

It is valid Python. It is more readable. And it evaluates x only once, which matters when x is a function call.


14. Dictionary Merging in One Line (Python 3.9+)

Before Python 3.9, merging two dictionaries was awkward. Now:

defaults = {"theme": "dark", "language": "en", "notifications": True}
user_prefs = {"theme": "light", "font_size": 14}

merged = defaults | user_prefs
print(merged)
# {'theme': 'light', 'language': 'en', 'notifications': True, 'font_size': 14}

The | operator merges them, with the right-hand dictionary winning on conflicts. This replaced multiple lines of {**dict1, **dict2} unpacking in my code.


15. Walrus Operator (:=) for Cleaner Loops

The walrus operator assigns a value inside an expression. It sounds strange until you see the problem it solves.

import re

lines = ["Error: disk full", "Info: all good", "Error: timeout", "Warning: slow"]

# Without walrus
for line in lines:
    match = re.search(r"Error: (.+)", line)
    if match:
        print(match.group(1))

# With walrus
for line in lines:
    if match := re.search(r"Error: (.+)", line):
        print(match.group(1))

Fewer lines. No double evaluation of re.search(). The walrus operator was added in Python 3.8, and it fits exactly into the kind of filtering loops you write all the time.


Where to Go From Here

Learning Python tricks is not the goal. The goal is writing code that solves real problems faster and more clearly. Every single trick above came from a moment where I was stuck, frustrated, or embarrassed by a code review comment.

The best way to internalize these is to pick three that you have never used and apply them in your next script. Not all fifteen. Just three. By the time you have genuinely used all fifteen in real projects, you will have naturally stumbled onto fifteen more.

That is how Python works. Every layer you peel back reveals another one beneath it.

Drop your questions in the comments.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top