Files
second-brain/Clippings/13 Python Shortcuts Every Developer Should Use for Faster Coding.md

7.6 KiB
Raw Permalink Blame History

title, source, author, published, created, description, tags
title source author published created description tags
13 Python Shortcuts Every Developer Should Use for Faster Coding https://python.plainenglish.io/13-python-shortcuts-every-developer-should-use-for-faster-coding-a9609daacc51
Abdur Rahman
2024-10-18 2024-10-29 You probably know a lot about Python language you worked many hours on improving your skills. Yet even after all that time, theres still something new in Python you might not know. This tiny trick…
clippings

And no, Im not talking about basic if __name__ == "__main__". Youre past that.

[

Abdur Rahman

](https://medium.com/@abdur-rahman?source=post_page---byline--a9609daacc51--------------------------------)

[

Python in Plain English

](https://python.plainenglish.io/?source=post_page---byline--a9609daacc51--------------------------------)

Photo by Icons8 Team on Unsplash

Youre a Python developer.

You probably know a lot about Python language you worked many hours on improving your skills. Yet even after all that time, theres still something new in Python you might not know.

Im about to share some tricks that will save time and make you code like a Python wizard.

Lets dive in!

1. Dictionary Default Values (dict.get())

Ever find yourself writing this sort of thing?

if key in my_dict:    value = my_dict[key]else:    value = default_value

Well, stop. Use dict.get() instead and move on with your life.

value = my_dict.get(key, default_value)

This tiny trick cuts down your lines and makes your code cleaner. Honestly, youll wonder why you ever did it the long way.

Avoid overthinking when simplicity can save time.

2. List Comprehensions for Speed and Style

You know list comprehensions but sometimes you still write loops because its a habit. You know it happens.

Heres a reminder to go back to the compact version:

squares = [x**2 for x in range(10)]

Want to throw in a condition? Pythons got your back:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

Its just cleaner and faster. Its like Python saying, “Why write a novel when you can tweet?”

3. Swap Variables Without Temp Variables

You might have been taught the ol temp variable swap back in the day. Forget that.

a, b = b, a

Yup, its that simple. Swaps two variables in a single line, no temp variable necessary. Pythons built for this kind of readability.

4. Unpacking in Style

Lets talk about multiple assignments. If you have a list of values you need to unpack into variables. Dont do it one at a time.

Use this shortcut instead.

numbers = [1, 2, 3]a, b, c = numbers

And heres a pro tip for those extra-long lists where you dont care about most values:

first, *middle, last = some_long_list

No more tedious index slicing — Python just reads your mind.

5. enumerate() to Simplify Loops

How often do you write this?

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

Thats more code than necessary. Pythons got your back with enumerate():

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

Thats it. Less clutter, more action.

Pro Tip: If youre looping over something and counting at the same time, youre doing it wrong unless youre using *enumerate()*.

6. Handle Exceptions Like a Pro with try/else

You know the try/except block. But did you know about try/else? This small feature helps in cleaning up exception handling. else runs when no exception is raised. Its better than putting everything in try because it makes clear what happens when nothing goes wrong.

Heres how it works:

try:    result = risky_operation()except SomeError:    handle_error()else:    handle_success()

7. Fast String Concatenation with .join()

If you are joining strings inside a loop, you are wasting CPU time. Every time you use +, it creates a new string. The better way is join(). Its fast and saves you time.

# Inefficientresult = ""for s in list_of_strings:    result += s# Efficientresult = ''.join(list_of_strings)

This is especially noticeable when working with large datasets. Dont sleep on this one.

8. The Walrus Operator (**:=**): Assign While You Check

Ah, the walrus operator. You may have heard about it in Python 3.8. It is helpful for making your code shorter and cleaner. It lets you assign variables as part of an expression. Especially in loops and conditionals.Instead of:

data = input("Enter something: ")if len(data) > 10:    print("Long input!")

Do this:

if (data := input("Enter something: ")).strip() and len(data) > 10:    print("Long input!")

See? One line, and youre already onto your next task.

9. **collections.defaultdict**: Because Normal Dictionaries Are So Last Year

Do KeyErrors frustrate you when a dictionary key doesnt exist? Fix this with defaultdict from collections. It automatically creates the first value when you access a new key. No need to check if the key exists.

Without it:

my_dict = {}if "counter" not in my_dict:    my_dict["counter"] = 0my_dict["counter"] += 1

With it:

from collections import defaultdictmy_dict = defaultdict(int)my_dict["counter"] += 1

Boom. One less headache to worry about.

10. The Underscore **_**: The Secret Keeper of the REPL

If youre using Python interactively (or in Jupyter), the last result can be quickly accessed. The underscore _ stores it for you. Handy, right?

>>> 5 * 25125>>> _ + 50  # Access the previous result175

This isnt just useful — its like having a secret superpower you didnt even know you had.

11. Context Managers: Stop Forgetting to Close Files

You probably think, “I always remember to close my files.” But just in case you forget, Pythons with statement will close the files for you. Its like a smart assistant.

Without it:

file = open('data.txt', 'r')try:    data = file.read()finally:    file.close()

With it:

with open('data.txt', 'r') as file:    data = file.read()

Less code, fewer bugs, and fewer excuses for leaving files open.

12. F-strings: Formatting, but Without the Nonsense

String formatting in Python used to be harder. You had to use .format() or % formatting. Now f-strings make everything better. They are faster and easier to read.

Instead of:

name = "Alice"greeting = "Hello, {}".format(name)

Use:

name = "Alice"greeting = f"Hello, {name}"

Simple, right? And the kicker? You can evaluate expressions directly inside the curly braces. Oh, and theyre faster, too. Just thought youd like to know.

13. **setdefault()**: Make Dictionaries Smarter

You already know dictionaries are fast. But did you know you can speed them up with setdefault()? It checks if a key exists and assigns a default value at the same time.

Old-school way:

my_dict = {}if "fruits" not in my_dict:    my_dict["fruits"] = []my_dict["fruits"].append("apple")

Streamlined way:

my_dict = {}my_dict.setdefault("fruits", []).append("apple")

If you havent been using this, youre probably wasting time — and nobody wants that.

If you think I missed any shortcut, drop it in the comments. Python can always get faster!