238 lines
7.6 KiB
Markdown
238 lines
7.6 KiB
Markdown
---
|
||
title: "13 Python Shortcuts Every Developer Should Use for Faster Coding"
|
||
source: "https://python.plainenglish.io/13-python-shortcuts-every-developer-should-use-for-faster-coding-a9609daacc51"
|
||
author:
|
||
- "[[Abdur Rahman]]"
|
||
published: 2024-10-18
|
||
created: 2024-10-29
|
||
description: "You probably know a lot about Python language you worked many hours on improving your skills. Yet even after all that time, there’s still something new in Python you might not know. This tiny trick…"
|
||
tags:
|
||
- "clippings"
|
||
---
|
||
## And no, I’m not talking about basic `if __name__ == "__main__"`. You’re past that.
|
||
|
||
[
|
||
|
||

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

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

|
||
|
||
Photo by [Icons8 Team](https://unsplash.com/@icons8?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com/?utm_source=medium&utm_medium=referral)
|
||
|
||
You’re 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, there’s still something new in Python you might not know.
|
||
|
||
I’m about to share some tricks that will save time and make you code like a Python wizard.
|
||
|
||
Let’s 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, you’ll 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 it’s a habit. You know it happens.
|
||
|
||
Here’s a reminder to go back to the compact version:
|
||
|
||
```
|
||
squares = [x**2 for x in range(10)]
|
||
```
|
||
|
||
Want to throw in a condition? Python’s got your back:
|
||
|
||
```
|
||
even_squares = [x**2 for x in range(10) if x % 2 == 0]
|
||
```
|
||
|
||
It’s just cleaner and faster. It’s 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, it’s that simple. Swaps two variables in a single line, no temp variable necessary. Python’s built for this kind of readability.
|
||
|
||
## 4\. Unpacking in Style
|
||
|
||
Let’s talk about multiple assignments. If you have a list of values you need to unpack into variables. Don’t do it one at a time.
|
||
|
||
Use this shortcut instead.
|
||
|
||
```
|
||
numbers = [1, 2, 3]a, b, c = numbers
|
||
```
|
||
|
||
And here’s a pro tip for those extra-long lists where you don’t 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
|
||
```
|
||
|
||
That’s more code than necessary. Python’s got your back with `enumerate()`:
|
||
|
||
```
|
||
for index, item in enumerate(my_list): print(index, item)
|
||
```
|
||
|
||
That’s it. Less clutter, more action.
|
||
|
||
> ***Pro Tip:*** *If you’re looping over something and counting at the same time, you’re doing it wrong unless you’re 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. It’s better than putting everything in `try` because it makes clear what happens when nothing goes wrong.
|
||
|
||
Here’s 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()`. It’s 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. Don’t 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 you’re already onto your next task.
|
||
|
||
## **9\.** `**collections.defaultdict**`**: Because Normal Dictionaries Are So Last Year**
|
||
|
||
Do KeyErrors frustrate you when a dictionary key doesn’t 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 you’re 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 isn’t just useful — it’s like having a secret superpower you didn’t 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, Python’s `with` statement will close the files for you. It’s 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 they’re faster, too. Just thought you’d 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 haven’t been using this, you’re probably wasting time — and nobody wants that.
|
||
|
||
If you think I missed any shortcut, drop it in the comments. Python can always get faster! |