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.
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 versionelif not sys.version_info >= (3, 5):# Kindly tell your user (s)he needs to upgrade because you're using 3.5 features3. 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) / 2my_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 sysmylist = range(0, 10000)print(sys.getsizeof(mylist))# 48myreallist = [x for x in range(0, 10000)]print(sys.getsizeof(myreallist))# 876326. Return multiple values – Functions can return tuples directly:
def get_user(id):# fetch user from databasereturn name, birthdatename, birthdate = get_user(4)7. Data classes (Python 3.7+) – Reduce boilerplate and get automatic __eq__ and __repr__:
from dataclasses import dataclass@dataclassclass Card:rank: strsuit: strcard = Card("Q", "hearts")print(card == card)# Trueprint(card.rank)# 'Q'print(card)# Card(rank='Q', suit='hearts')8. Swap variables – One‑liner tuple unpacking:
a = 1b = 2a, b = b, aprint(a)# 2print(b)# 19. 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 Countermylist = [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 = 10if 5 < x < 15:print("Yes")16. Add colored terminal output with colorama :
from colorama import Fore, Back, Styleprint(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 parselogline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'timestamp = parse(logline, fuzzy=True)print(timestamp)# 2020-01-01 00:00:0118. Integer division differences – Python 2 uses floor division for /, Python 3 uses true division; use // for floor division in Python 3:
# Python 25 / 2 = 25 / 2.0 = 2.5# Python 35 / 2 = 2.55 // 2 = 219. Detect character encoding with chardet :
pip install chardetchardetect somefile.txtsomefile.txt: ascii with confidence 1.020. Create a simple progress bar :
pip install progressfrom progress.bar import Barbar = Bar('Processing', max=20)for i in range(20):# Do some workbar.nextbar.finish21. Quick web server – Serve current directory: python3 -m http.server These tips collectively help Python developers write cleaner, more efficient, and more maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
