Fundamentals 17 min read

30 Python Best Practices, Tips, and Tricks

This article presents thirty practical Python best‑practice tips covering version checks, IPython usage, list comprehensions, memory inspection, multiple return values, data classes, variable swapping, dictionary merging, string manipulation, ternary operators, counters, comparison chaining, color output, date parsing, integer division, character‑set detection and more, each illustrated with concise code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
30 Python Best Practices, Tips, and Tricks

The author shares thirty concise Python best‑practice tips aimed at improving code quality, readability, and efficiency for everyday programmers.

1. Python version – Python 2 is no longer supported; ensure scripts run on Python 3.

2. Check minimum Python version – Use version checks in code:

if not sys.version_info > (2, 7):
# berate your user for running a 10 year python version
elif not sys.version_info >= (3, 5):
# Kindly tell your user (s)he needs to upgrade because you're using 3.5 features

3. IPython – An enhanced interactive shell with magic commands such as %cd, %edit, %env, %pip install [pkgs], %time, %timeit, and the ability to reference previous inputs via In and Out.

4. List comprehensions – Replace loops with concise expressions:

[ expression for item in list if conditional ]
mylist = [i for i in range(10)]
print(mylist)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def some_function(a):
return (a + 5) / 2
my_formula = [some_function(i) for i in range(10)]
print(my_formula)
# [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
filtered = [i for i in range(20) if i%2==0]
print(filtered)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

5. Inspect object memory usage – Use sys.getsizeof:

import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# 48
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632

6. Return multiple values – Functions can return tuples directly:

def get_user(id):
# fetch user from database
return name, birthdate
name, birthdate = get_user(4)

7. Data classes (Python 3.7+) – Reduce boilerplate and get automatic __eq__ and __repr__:

from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
# Card(rank='Q', suit='hearts')

8. Swap variables – One‑liner tuple unpacking:

a = 1
b = 2
a, b = b, a
print(a)
# 2
print(b)
# 1

9. Merge dictionaries (Python 3.5+) :

dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print(merged)
# {'a': 1, 'b': 3, 'c': 4}

10. Capitalize string titles :

mystring = "10 awesome python tricks"
print(mystring.title)
# '10 Awesome Python Tricks'

11. Split strings into lists :

mystring = "The quick brown fox"
mylist = mystring.split(' ')
print(mylist)
# ['The', 'quick', 'brown', 'fox']

12. Join list into string :

mylist = ['The', 'quick', 'brown', 'fox']
mystring = " ".join(mylist)
print(mystring)
# 'The quick brown fox'

13. Ternary operator : x = "Success!" if (y == 2) else "Failed!" 14. Count element frequencies with Counter :

from collections import Counter
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
c = Counter(mylist)
print(c)
# Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})
print(Counter("aaaaabbbbbccccc"))
# Counter({'a': 5, 'b': 5, 'c': 5})

15. Chain comparison operators :

x = 10
if 5 < x < 15:
print("Yes")

16. Add colored terminal output with colorama :

from colorama import Fore, Back, Style
print(Fore.RED + 'some 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')

17. Date handling with python-dateutil :

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

18. Integer division differences – Python 2 uses floor division for /, Python 3 uses true division; use // for floor division in Python 3:

# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
# Python 3
5 / 2 = 2.5
5 // 2 = 2

19. Detect character encoding with chardet :

pip install chardet
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0

20. Create a simple progress bar :

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

21. Quick web server – Serve current directory: python3 -m http.server These tips collectively help Python developers write cleaner, more efficient, and more maintainable code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceprogrammingbest practicesData Structurescode snippetsTips
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.