30 Essential Python Tricks Every Developer Should Know
This article compiles thirty practical Python tips and best‑practice snippets—ranging from version checks, IPython shortcuts, list comprehensions, memory profiling, data classes, swapping variables, dictionary merging, string manipulation, emoji handling, image display, map usage, set operations, counters, chained comparisons, terminal colors, date parsing, integer division nuances, to character‑set detection—each illustrated with clear code examples for immediate use.
1. Python version
Since January 1 2020 the official Python project no longer supports Python 2; all examples in this article require Python 3.
2. Check minimum Python version
You can guard your script against old versions:
if not sys.version_info > (2, 7):
# berate your user for running a 10‑year old python version
elif not sys.version_info >= (3, 5):
# kindly tell your user they need to upgrade because you're using 3.5 features3. IPython
IPython is an enhanced interactive shell with auto‑completion and many useful magic commands:
%cd – change the current working directory
%edit – open an editor and execute the edited code on close
%env – show current environment variables
%pip install [pkgs] – install packages without leaving the shell
%time and %timeit – measure execution time of Python code
You can also retrieve the output of a previous command via Out[3] and install IPython with:
pip3 install ipython4. List comprehensions
Use list comprehensions to build lists concisely: [expression for item in list if conditional] Examples:
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 to see how much memory a container occupies:
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist)) # 48
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist)) # 876326. Return multiple values
Functions can return several values directly:
def get_user(id):
# fetch user from database
return name, birthdate
name, birthdate = get_user(4)If more than three values are needed, consider returning a data class.
7. Data classes (Python 3.7+)
Data classes reduce boilerplate, provide __eq__, __repr__, and type hints:
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
a = 1
b = 2
a, b = b, a
print(a) # 2
print(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 strings
mystring = "10 awesome python tricks"
print(mystring.title()) # 10 Awesome Python Tricks11. Split string into list
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 fox13. Emoji handling
pip3 install emoji
import emoji
result = emoji.emojize('Python is :thumbs_up:')
print(result) # Python is 👍
result = emoji.demojize('Python is 👍')
print(result) # Python is :thumbs_up:14. List slicing
a[start:stop:step]Defaults: start = 0, stop = end, step = 1.
first_two = [1, 2, 3, 4, 5][0:2]
print(first_two) # [1, 2]
steps = [1, 2, 3, 4, 5][0:5:2]
print(steps) # [1, 3, 5]
mystring = "abcdef"[::2]
print(mystring) # ace15. Reverse string/list
revstring = "abcdefg"[::-1]
print(revstring) # gfedcba
revarray = [1, 2, 3, 4, 5][::-1]
print(revarray) # [5, 4, 3, 2, 1]16. Display images (Pillow)
pip3 install Pillow
from PIL import Image
im = Image.open("kittens.jpg")
im.show()
print(im.format, im.size, im.mode) # JPEG (1920, 1357) RGB17. map function
def upper(s):
return s.upper()
mylist = list(map(upper, ['sentence', 'fragment']))
print(mylist) # ['SENTENCE', 'FRAGMENT']
list_of_ints = list(map(int, "1234567"))
print(list_of_ints) # [1, 2, 3, 4, 5, 6, 7]18. Unique elements with set
mylist = [1,1,2,3,4,5,5,5,6,6]
print(set(mylist)) # {1, 2, 3, 4, 5, 6}
print(set("aaabbbcccdddeeefff")) # {'a', 'b', 'c', 'd', 'e', 'f'}19. Most frequent value
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count)) # 420. Progress bar
pip3 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. Underscore in IPython
In[1]: 3 * 3
Out[1]: 9
In[2]: _ + 3
Out[2]: 1222. Quick web server
python3 -m http.server23. Multi‑line strings
s1 = """Multi line strings can be put
between triple quotes. It's not ideal
when formatting your code though"""
print(s1)
s2 = ("You can also concatenate multiple
" +
"strings this way, but you'll have to
" +
"explicitly put in the newlines")
print(s2)24. Ternary operator
x = "Success!" if (y == 2) else "Failed!"25. Count elements with Counter
from collections import Counter
mylist = [1,1,2,3,4,5,5,5,6,6]
c = Counter(mylist)
print(c) # Counter({5: 3, 1: 2, 6: 2, 2: 1, 3: 1, 4: 1})
print(Counter("aaaaabbbbbccccc")) # Counter({'a':5,'b':5,'c':5})26. Chained comparisons
x = 10
if 5 < x < 15:
print("Yes")27. Terminal colors (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')28. Date handling (python‑dateutil)
pip3 install 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:0129. Integer division
Python 2 uses / for integer division; Python 3 uses // for floor division and / for true division.
# Python 2
5 / 2 # 2
5 / 2.0 # 2.5
# Python 3
5 / 2 # 2.5
5 // 2 # 230. Detect charset with chardet
pip install chardet
chardetect somefile.txt
# output: somefile.txt: ascii with confidence 1.0Python 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.
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.
