Python Is Easier Than You Think, Start With These Tricks

Python Easy Tricks - My Code Diary

Python Is Easier Than You Think. Start With These Tricks

By My Code Diary


I used to stare at Python code like it was written in ancient Greek. Nested loops, list comprehensions, and lambda functions all of it felt like something only a genius could understand. Then one day, while debugging a script, I accidentally discovered something that saved me three hours of work. It was a one-liner. A single line. That night changed how I thought about Python forever.

Here’s the thing nobody tells you when you start learning Python: the language isn’t hard. The way it’s taught is hard. Most tutorials dump syntax on you before they show you why any of it matters. This article flips that. Every trick here comes from a real problem I ran into and the shortcut I found to solve it.


1. Stop Writing Loops Just to Build Lists

Most beginners write a for loop, create an empty list, and append items one by one. It works. But Python has a cleaner way.

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

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

List comprehensions feel weird at first, but once they click, you will never go back. Think of them as a sentence: “Give me i-squared, for every i in range 10.” That’s exactly what the code says.


2. Swap Two Variables Without a Temp Variable

In most languages, swapping two variables means creating a third one to hold the value temporarily. In Python, you can skip all of that.

a = 5
b = 10
a, b = b, a
print(a, b)  # 10 5

This is called tuple unpacking. Python handles the swap behind the scenes. It is a small thing, but it shows how readable Python can be when you learn its idioms.


3. Use enumerate() Instead of Tracking Index Manually

How many times have you written this?

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

There is a built-in function that does this automatically.

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

enumerate() gives you both the index and the value in one clean line. No counter variable, no extra logic.


4. Read Files Without Worrying About Closing Them

Early on, I wrote a script that opened a file, processed it, but forgot to close it. The file got locked, the script failed, and I spent an hour figuring out why. The fix is with statement.

with open("data.txt", "r") as f:
    content = f.read()

When the block ends, Python closes the file automatically. No manual cleanup. No forgotten close calls. This is especially important when your script opens dozens of files in a loop.


5. Default Values in Functions Save You From Bugs

Here is a classic Python trap. You set a mutable object as a default argument, and things start behaving strangely.

# This is a bug waiting to happen
def add_item(item, my_list=[]):
    my_list.append(item)
    return my_list

The list gets shared across every call. Use None as the default instead.

def add_item(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list

This is one of those bugs that looks fine until production, and then it causes chaos.


Pro Tip: “Programs must be written for people to read, and only incidentally for machines to execute.” – Harold Abelson

Write code your future self can understand at 2 AM without caffeine.


6. Use zip() to Loop Over Two Lists at Once

Pairing two lists used to mean indexing into both with the same counter. Now I use zip().

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 72]

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

Clean, readable, and it works on any two iterables. If one list is shorter, zip() stops at the shorter one worth remembering.


7. Dictionary .get() Prevents KeyErrors

Accessing a dictionary key that does not exist crashes your program with a KeyError. Many beginners wrap everything in try-except blocks to handle this. There is a simpler way.

user = {"name": "Alice", "age": 30}

# This crashes if "email" doesn't exist
print(user["email"])

# This returns None silently
print(user.get("email"))

# Or return a default
print(user.get("email", "No email found"))

.get() is one of those methods that feels obvious in hindsight but saves you from dozens of crashes once you start using it.


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

I have seen beginners use %s, .format(), and concatenation with + all in the same codebase. Pick one. Make it f-strings.

name = "Alice"
age = 30

# Old ways
print("Hello, %s. You are %d years old." % (name, age))
print("Hello, {}. You are {} years old.".format(name, age))

# Clean modern way
print(f"Hello, {name}. You are {age} years old.")

f-strings are faster, easier to read, and you can put any Python expression directly inside the curly braces. They were introduced in Python 3.6 and there is no good reason to use anything else.


9. Automate the Boring Stuff With os and pathlib

This is where Python stops being a learning exercise and starts becoming genuinely useful. The pathlib library lets you work with files and folders in a way that reads almost like English.

from pathlib import Path

folder = Path("my_documents")

# List all PDF files in a folder
for file in folder.glob("*.pdf"):
    print(file.name)

A few years ago, I wrote a script that went through 200 folders of client reports and renamed every file to follow a consistent format. What would have taken a full workday took 20 minutes to write and 30 seconds to run. That is the real promise of Python.


What’s Next?

None of these tricks require advanced knowledge. They just require knowing they exist. That is what separates someone who writes Python from someone who writes good Python not raw intelligence, but exposure to the right patterns at the right time.

Pick two or three of these and use them in your next project. Do not try to memorize them all at once. Real learning happens when you use something to solve an actual problem, not when you read about it.

The best Python programmers are not the ones who know the most. They are the ones who stopped overcomplicating things first.

Drop a comment if any of these clicked for you, or if there is a trick you think should have made the list.

Leave a Comment

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

Scroll to Top