35 Best Python Tips and Tricks For Writing Better Code

Share on:

Thirty-five practical tricks to make your Python cleaner, faster, and a pleasure to read.

Updated October 2026: five tips now use newer Python features (the walrus operator, match, functools.cache, dataclasses and pathlib), three gained newer syntax, and every example was rechecked.

Most Python code works. The real question is whether you, or the next person, can still read it six months later. Code that is short and clear is easier to understand, maintain and extend, and Python has a neat trick for almost every long-winded pattern.

In this article, I’ll take you through 35 Python tips and tricks for writing better Python code, from one-line conditionals and f-strings to sets, generators, dataclasses, pathlib and match. Each tip shows the long way and the Pythonic way side by side, so you’ll come away with habits you can use in your very next pull request.

1. Python Tips for Conditional Expressions / Ternary Expression

Many times we use the if…else statement to check a condition and based on that we assign a value to a variable. That takes a few lines, and if you do it often, your program gets long. A ternary expression does the same job in one line.

A ternary expression checks the condition and completes the assignment with just one line of code. As it’s a one-liner, it makes your code even more concise.

num = 7
# Normal Programmers
if num % 2 == 0:
      result = "Number is divided by 2"
else:
      result = "Number is not divided by 2"
# Mentos Programmers
result = "Number is divided by 2" if num % 2 == 0 else  "Number is not divided by 2"

2. Use Python for multiple variable assignments

You can assign multiple variables with the same value or multiple values in a single line in python. In the first example, we are assigning 10 to the x, y, and z variables. We can do this by using this syntax.

 variable 1 = variable 2 = variable 3 = value

Similarly, if you are assigning different values then you try out this syntax.

 variable 1, variable 2, variable 3 = value1, value2, value3
# Normal Programmers
x = 10
y = 10
z = 10 
# Mentos Programmers
x = y = z = 10
x, y, z = 10, 20, 30

3. Working with Large Numbers with python

Now let us discuss my favorite trick. Have you ever worked with large numbers? 1000000000 or 1,000,000,000; Which one is more readable? The second one, right? But if we try to do that in Python like num1=1,000,000,000, we would get an error.

But there’s another method to do the same. We can use _ to separate the digits which do not affect our program. And we can use: inside the f string to separate the output digits by a comma. The following code demonstrates the same.

num1 = 1_000_000_000     # 1 billion
num2 = 10_000_000        # 10 million
total = num1 + num2
print(f'{total:,}')      # To separate the output digits with comma
# Output
# 1,010,000,000

4. Use list comprehension instead of raw for-loops

Have you ever worked with a list or tuple where you need to perform some operations on them?

But in the end, you wanted a list as an output? Then the next trick can definitely help you next time to save time and write concise code.

arr = [1, 2, 3, 4, 5, 6]
res = []
# Instead of this
for num in arr:
    if num % 2 == 0:
        res.append(num * 2)
    else:
        res.append(num)
# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]

5. Iterate with enumerate() instead of range(len())

Sometimes you need both the item and its index while looping over a list. You can use range(len()), but then you have to look each item up yourself. enumerate() gives you both at once.

enumerate() takes any iterable, like a list or tuple, and gives you (index, value) pairs.

data = [1,2,3,-4,5]
# Normal Programmers
for i in range(len(data)):
      if data[i] < 0:
           data[i] = 0
# Mentos Programmers
for i, num in enumerate(data):
      if num < 0:
          data[i] = 0

6. Inputting Secret Information

Let’s say you are taking a username and password as input from the user. You would surely go with the following approach.

uname = input('Enter Username: ')
pwd = input('Enter password: ')
print('Logging In....')
#output
"""
Enter Username: Anup
Enter password: 12345
Loggin In..
"""

But anyone can see that password, and that breaches the security. To keep it hidden, use getpass() from the getpass module: it reads the password without showing it on screen.

from getpass import getpass
uname = input('Enter Username: ')
pwd = getpass('Enter password: ')
print('Logging In....')
#output
"""
Enter Username: Anup
Enter password: *****
Loggin In..
"""

7. List embedding with a nested loop in python

If you need to create a list while iterating through a list or tuple you can use this approach.

list1 = [1,2,3]
list2 = ['a', 'b']
result = [(x, y) for x in list1 for y in list2]
for x, y in result: print(x, y)
# Output
"""
1 a
1 b
2 a
2 b
3 a
3 b
"""

8. Use the walrus operator (:=) to assign inside an expression

Since Python 3.8, the walrus operator := assigns a value and returns it in the same expression. It removes the repeated line before a loop, and it avoids computing the same value twice in a comprehension.

# Instead of this
command = input("Enter a command: ")
while command != "quit":
    print(f"Running {command}")
    command = input("Enter a command: ")

# Use this
while (command := input("Enter a command: ")) != "quit":
    print(f"Running {command}")

# Keep only the squares above 50, computing each square once
values = [3, 8, 5, 10]
big_squares = [sq for v in values if (sq := v * v) > 50]
print(big_squares)
# Output: [64, 100]

9. Make your search faster

If you check whether items are in a collection again and again, use a set. A lookup in a set takes constant time on average (O(1)), while a list has to scan its items (O(n)).

# Instead of this 
l = ['a', 'e', 'i', 'o', 'u']
def is_vowel(char):
    if char in l:
        print("Vowel")
# Use this
s = {'a', 'e', 'i', 'o', 'u'}
def is_vowel(char):
    if char in s:
        print("Vowel")

Also Read: Zero to Mastery Decision Tree Guide to Move in Data Science

10. Variable Unpacking

In python, variable unpacking is the process of assigning an iterable of values to a list or tuple of variables using a single assignment statement.

x, y = [1, 2]
# x = 1, y = 2
x, *y = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4, 5]
x, *y, z = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4], z = 5

11. Save Memory with Generators

Let’s say we have a very large list with 100000 items and we want to calculate the sum over all the items. The list is not always the best choice. Of course, you can do this with a list but you might waste lots of RAM.

This can make a huge difference when working with large data, so it’s always good to keep the generator in mind!

import sys 
my_list = [i for i in range(100000)]
print(sys.getsizeof(my_list), 'bytes') # 824456 bytes
my_gen = (i for i in range(100000))
print(sys.getsizeof(my_gen), 'bytes') # 112 bytes

12. Lambda Function to filter NumPy array

We can easily filter a NumPy array or DataFrame series using the lambda function. In the below example, I’m filtering a NumPy array of books and ratings which have ratings more than 3.9.

## Dependencies
import numpy as np
## Data looks like [title, rating]
books = np.array([['Coffee Break NumPy', 4.6],
['Lord of the Rings', 5.0], ['The Alien Artifact', 1.8], 
['Winnie-the-Pooh', 3.9],
['The Betrothed by Kiera Cass',2.9],
 ['Forbidden', 3.0], 
['Coffee Break Python', 4.7]]) 
predict_bestseller = lambda x, y : x[x[:,1].astype(float) > y] 
print(predict_bestseller(books, 3.9))
# Output
"""
[['Coffee Break NumPy' '4.6']
 ['Lord of the Rings' '5.0']
 ['Coffee Break Python' '4.7']]
"""

13. Swapping values between two variables

Let’s say you have a variable x hold 10 and y holds 20. Now you want to swap the values between x and y. So, y should hold 20 and x should hold 10.

Python has an easy trick up its sleeve for this.

x, y = 10, 20
# Normal Programmers
temp = x
x = y
y = temp
# Mentos Programmers
x, y = y, x

14. Filter unique values with Sets

If your list may contain duplicates and you only want the unique values, convert it to a set: a set keeps each value only once. If the original order matters, use list(dict.fromkeys(items)) instead.

my_list = [1,2,3,3,'3',4,5,6,7,7,7,'a','a','a']
my_set = set(my_list) # removes duplicates
print(my_set) 
# Output
"""
{1, 2, 3, 4, 5, 6, 7, 'a', '3'}
"""

15. Use match for structural pattern matching

Python 3.10 added match. It is more than a switch statement: it can compare the shape of a value, such as the words in a command, and pull parts out of it at the same time.

def handle(command):
    match command.split():
        case ["go", direction]:
            return f"Going {direction}"
        case ["pick", "up", item]:
            return f"Picked up {item}"
        case ["quit" | "exit"]:
            return "Goodbye"
        case _:
            return "Unknown command"

print(handle("go north"))     # Going north
print(handle("pick up key"))  # Picked up key
print(handle("exit"))         # Goodbye

16. Cache slow function calls with functools.cache

If a function is called again and again with the same arguments, @cache (Python 3.9+) stores each result and returns it instantly the next time. A recursive Fibonacci function becomes fast without any other change.

from functools import cache   # Python 3.8 or older: lru_cache(maxsize=None)

@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))
# Output: 23416728348467685 (instantly; without @cache it would practically never finish)

17. Multiple Comparisons without logical operator

Using comparison operators we compare two values. Its return is true or false based on the comparison. But sometimes if you need to find a value between two or more conditions then we use logical operators like and, or, not to combine conditions.

For example, say x should be between 0 and 100. That’s two conditions, 0 < x and x < 100, and you’d usually join them with and. In Python you can simply write 0 < x < 100.

x = 42
# Instead of this
if 0 < x and x < 100:
    print(f"{x} is a 2 digit number")
# Use this
if 0 < x < 100:
    print(f"{x} is a 2 digit number")

Similarly, if you need a bunch of conditions then there is no need to combine them using logical operators. You can use a list or tuple with these elements and using it you can check all of them.

b = "Wed"
# Instead of this
if b == "Mon" or b == "Wed" or b == "Fri" or b == "Sun":
    print("Gym day")
# Use this
if b in "Mon Wed Fri Sun".split():
    print("Gym day")

Till now we compared one variable. To check conditions on several variables, use all() or any(). As the names suggest, all() is true only when every condition is true, like and, and any() is true when at least one is, like or.

a, b, c = 3, 7, 4
# Instead of this
if a < 10 and b > 5 and c == 4:
    print("all three are true")
# Use this all()
if all([a < 10, b > 5, c == 4]):
    print("all three are true")
# Instead of this
if a < 10 or b > 5 or c == 4:
    print("at least one is true")
# Use this any()
if any([a < 10, b > 5, c == 4]):
    print("at least one is true")

18. The best way to iterate over a dictionary in Python

If you have a dictionary of fruit prices. If you want to iterate through it then follow the below approach.

fruit_price = {
    "apple": 200,
    "banna": 20
}
# Instead of this
for key in fruit_price:
    print(key, fruit_price[key])
# Do this
for fruit, price in fruit_price.items():
    print(fruit, price)

19. Better way of String Formatting

Let’s say we have different variables which have different data types. Now if we want to create a string value for all of these variables then we can either convert all of these values to strings. Or we can be using String formatting.

There are three ways to do string formatting. One of them is F-Strings which are introduced in python 3. String formatting is a great new way to format strings and is more readable, faster, concise, and less prone to error than other ways of formatting!

name = "3080ti"
price = 97000
# Instead of this
print(name + " costs "+str(price))
# Use this
print(f"{name} costs {price}.")
# Or this
print("{} costs {}.".format(name, price))
# Or this
print("%s costs %d." %(name, price))

Since Python 3.8, an f-string can also print the expression next to its value, which is handy while debugging:

price = 97000
print(f"{price=}")              # price=97000
print(f"{price * 1.18=:.2f}")   # price * 1.18=114460.00

20. The Dir Function

It is a powerful inbuilt function in python, which returns a list of the attributes and methods of any object i.e. functions, modules, strings, lists, dictionaries, etc.

This can be very useful when having little to no information about the module and helps to learn new modules faster.

numbers = [1, 2, 3, 4, 5]
print(dir(numbers))
# Output
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
"""

21. Use a Counter for Element Counting

If you want to count how many times unique elements occur; you can use Counter from collections. Counter returns a counter object which stores key-value pairs. The Key will be the word and the value will be the frequency of the word.

words = ['an', 'boy', 'girl', 'an', 'boy', 'dog', 'cat', 'Dog', 'CAT', 'an','GIRL', 'AN', 'dog', 'cat', 'cat', 'bag', 'BAG', 'BOY', 'boy', 'an']
# Instead of this
unique_words = {x.lower() for x in set(words)}
for word in unique_words:
     print(f"* Count of {word}: {words.count(word)}")
 
# Output
"""
Count of girl: 1
Count of boy: 3
Count of dog: 2
Count of an: 4
Count of cat: 3
Count of bag: 1
"""
# Use this
from collections import Counter
word_counter = Counter(x.lower() for x in words)
print("Word Counts:", word_counter)
# Output
"""
Word Counts: Counter({'an': 5, 'boy': 4, 'cat': 4, 'dog': 3, 'girl': 2, 'bag': 2})
"""

22. Merge two dictionaries

Using ** unpacking, we can easily merge two or more dictionaries into a new one.

d1={"A": 10, "B": 20, "C": 30}
d2={"X": 100, "Y": 200, "Z": 300}
d3={**d1, **d2}
print(d3)
# Output
"""
{'A': 10, 'B': 20, 'C': 30, 'X': 100, 'Y': 200, 'Z': 300}
"""

From Python 3.9 you can also use the | operator:

d3 = d1 | d2    # a new merged dictionary
d1 |= d2        # or update d1 in place

23. Use dataclasses for classes that mostly hold data

A @dataclass writes the boring parts of a class for you: __init__, a readable __repr__ and __eq__.

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

p = Point(3, 4)
print(p)                  # Point(x=3, y=4)
print(p == Point(3, 4))   # True
print(Point(5))           # Point(x=5, y=0.0)

24. Reverse a string with negative slicing

If you want to reverse a string with the help of negative slicing; you can easily do it.

sentence = "This is just a test"
reversed = sentence[::-1]
print(reversed)
# tset a tsuj si sihT

25. Squash a list of strings into one string

Let’s say you have a list of words and you want to join all of them together as a string. Using the string join() method we can do that. Also, we can easily add space between two words.

words =['The', 'quick', 'brown', 'fox']
combined = " ".join(words)
print(combined)
# Output
"""
The quick brown fox
"""

26. Find the Most Frequent Element in a List

If you need the most frequent element in a list, this one-liner does it. It counts the list again for every distinct value, so on long lists use Counter(test).most_common(1) from tip 21 instead.

test = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]
most_frequent = max(set(test), key = test.count)
print(most_frequent)
# Output
"""
2
"""

27. Work with file paths using pathlib

pathlib treats paths as objects. The / operator joins them correctly on every operating system, and reading, writing and searching for files each take one line.

from pathlib import Path

reports = Path("data") / "reports"
reports.mkdir(parents=True, exist_ok=True)

(reports / "summary.txt").write_text("All good")
for file in reports.glob("*.txt"):
    print(file.name, file.stat().st_size)
# Output: summary.txt 8

28. Using map()

One of Python’s built-in functions is called map(). The syntax for map() is:

map(function, something_iterable)

In the example below we will convert a string of numbers into int and then convert them into a list of items.

# Convert a string representation of
# a number into a list of ints.
list_int = list(map(int, "1234567"))
print(list_int)
# Output
"""
[1, 2, 3, 4, 5, 6, 7]
"""

29. Create a progress bar

Let’s say you are building a command-line Interface(CLI) and performing a certain operation takes some time. If we don’t show any update, the user might think the program has frozen or something went wrong.

A progress bar fixes that. Building one by hand takes work, but the progress package does it for you.

Terminal demo of the Python progress package: Bar, ChargingBar, FillingSquaresBar, IncrementalBar and ShadyBar progress bars plus spinners filling up

You can install it with pip.

pip install progress

You can create a progress bar with minimal effort:

from progress.bar import Bar
bar = Bar('Processing', max=20)
for i in range(20):
    # Do some thing
    bar.next()
bar.finish()

The progress package still works, but most Python projects today use tqdm: install it with pip install tqdm and wrap any loop, as in for i in tqdm(range(20)):.

30. Customize the terminal/cmd with colors

If you’re building a CLI and want it to look better and be easier to use, try Python’s Colorama package. It adds color to your terminal output.

You can install Colorama with pip.

pip install colorama

Now we can easily print some colorful text on the terminal

from colorama import Fore, Back, Style
print(Fore.RED + 'ATT in red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
customize terminal with colorama python
output

31. Getting the Date and time from the log file

If you ever have to deal with log files then you must know it’s always a headache to get dates and times from a log file. But there is an easy solution to this problem. The python-dateutil module provides powerful extensions to the standard DateTime module.

You can install it with:

pip install python-dateutil

Its fuzzy parsing is the useful part here: it finds the date and time inside a log line and ignores the rest.

from dateutil.parser import parse
logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'
timestamp = parse(logline, fuzzy=True)
print(timestamp)
# Output
"""
2020-01-01 00:00:01
"""

32. Sorting objects by multiple keys

If we have a list of dictionaries have two keys ‘name’, and ‘age’. Now if we don’t just want to sort it by name or age; we want to sort it by both fields.

In SQL, this would be a query like SELECT * FROM people ORDER by name, age.

We can easily do this using operator.itemgetter(). In the below example we sort a list of dictionaries by name, then by age.

people = [
{ 'name': 'John', "age": 64 },
{ 'name': 'Janet', "age": 34 },
{ 'name': 'Ed', "age": 24 },
{ 'name': 'Sara', "age": 64 },
{ 'name': 'John', "age": 32 },
{ 'name': 'Jane', "age": 34 },
{ 'name': 'John', "age": 99 },
]
# Sorting by name and age
import operator
people.sort(key=operator.itemgetter('age'))
people.sort(key=operator.itemgetter('name'))
#Output
"""
[
 {'name': 'Ed',   'age': 24},
 {'name': 'Jane', 'age': 34},
 {'name': 'Janet','age': 34},
 {'name': 'John', 'age': 32},
 {'name': 'John', 'age': 64},
 {'name': 'John', 'age': 99},
 {'name': 'Sara', 'age': 64}
]
"""

33. Sort Complex Iterables With Sorted()

Using the python sorted() function we can sort a list or tuple without modifying the original sequence.

Syntax:

sorted(iterable, key, reverse)
key it's an optional value which by default None.
reverse by default it is  false. If it's set true, then the iterable would be sorted in descending order.

Below we have two examples in the first example we are sorting the list by numbers. In the second example, the dictionary is sorted by age.

num_list = [3,2,6,33,11,64,99,15]
num_sorted = sorted(num_list)
data = [{"name" : "Joy", "Age" : 19}, 
        { "name" : "Lisa", "Age" : 17},
        { "name" : "Jack", "Age" : 21}]
sorted_data = sorted(data, key = lambda x : x['Age'])
print("Sorted list:", num_sorted)
print("Sorted dictionary list:", sorted_data)
"""
Output:Sorted list: [2, 3, 6, 11, 15, 33, 64, 99]
Sorted dictionary list: [{'name': 'Lisa', 'Age': 17}, {'name': 'Joy', 'Age': 19}, {'name': 'Jack', 'Age': 21}]
"""

34. Use of the get() method in Dictionary

If we want to extract a value from a dictionary then using [] we can get it. But if the key doesn’t exist, it raises a KeyError.

We can extract a value from a dictionary in a much better way using the get() method.

Syntax:

dictionary.get(key, value)
key - key of the item you are looking for.
value - default value if the key does not exist.

In the below example we have a dictionary called the car.

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print("Brand:", car.get("brand"))
print("Type:", car.get("type", "Not Found"))
"""
Output:Brand: Ford
Type: Not Found
"""

35. Use of Enum in Python

Python’s enum module (short for enumerations) is a clean way to handle a fixed set of values that won’t change, like days of the week or order statuses.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color.RED.name)
print(Color.RED.value)
print(list(Color))
# Output
"""
RED
1
[<Colors.RED: 1>, <Colors.GREEN: 2>, <Colors.BLUE: 3>]
"""
# We can also create a Enum in one line
Colors = Enum('Colors', 'RED GREEN BLUE')
print(Colors.RED.name)
print(Colors.RED.value)
print(list(Colors))
# Output
"""
RED
1
[<Colors.RED: 1>, <Colors.GREEN: 2>, <Colors.BLUE: 3>]
"""

Conclusion

Tried my best to keep this article as comprehensive as possible, but it’s possible that some useful tips are missing. If so, please share it in the comment section, I will be happy to know about it. Be curious, keep learning and stay willing to learn new things until we meet next time! 

If you like this article and wish to connect with me follow on Linkedin. Share your thoughts in the comments section below, what did you find interesting in this article.

Now I’m leaving you with an interesting thought from Lao Tzu. Until next time, take care of yourself, your family, and your friends, and stay safe and healthy!

“To attain knowledge, add things every day. To attain wisdom, remove things every day.”

Lao Tzu.
Anup-Das-Anuptechtips

I write about System Design, Backend Architecture, GenAI Infrastructure, and scalable Python applications.