Fundamentals 19 min read

30 Essential Python Tips & Tricks Every Developer Should Know

This article presents a curated collection of practical Python tips—from version checks and IPython magic commands to list comprehensions, data classes, dictionary merging, progress bars, and more—each illustrated with concise code snippets and clear explanations for immediate use.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
30 Essential Python Tips & Tricks Every Developer Should Know

1. Python Version

Reminder: Python 2 is no longer supported since January 1, 2020; the examples in this article require Python 3, so upgrade if you are still using 2.7.

2. Check Minimum Python Version

You can verify the interpreter version in code to ensure compatibility:

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

IPython is an enhanced interactive shell offering auto‑completion and many useful magics such as %cd (change directory), %edit (open editor), %env (show environment variables), %pip install [pkgs] (install packages without leaving the shell), and %time / %timeit (measure execution time). Use In and Out objects to reference previous inputs and outputs.

4. List Comprehensions

Use list comprehensions to build lists concisely: [expression for item in iterable if condition] 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. Check Object Memory Usage

Use sys.getsizeof to inspect memory consumption:

import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))  # 48 bytes (range object is memory‑efficient)
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))  # 87632 bytes (actual list)

6. Return Multiple Values

Functions can return multiple values without wrapping them in a container:

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

For more than three values, 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)  # 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 Strings

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

11. 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 fox

13. Emoji

Install emoji and use it to add or remove emojis:

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]   # [1, 2]
steps = [1,2,3,4,5][0:5:2]     # [1, 3, 5]
mystring = "abcdef"[::2]      # 'ace'

15. Reverse String or List

revstring = "abcdefg"[::-1]
print(revstring)  # gfedcba
revarray = [1,2,3,4,5][::-1]
print(revarray)   # [5,4,3,2,1]

16. Show 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) RGB

17. 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)  # 4

20. Progress Bar (progress package)

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 Interactive Shell

In [1]: 3 * 3
Out[1]: 9
In [2]: _ + 3
Out[2]: 12

22. Quick Web Server

python3 -m http.server

23. 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 Conditional 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. Colored Output (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:01

29. Integer Division

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

30. Detect Charset (chardet)

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

These 30 tips constitute a handy “new‑year gift” for Python developers; feel free to share your own tricks in the comments.

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.

Python
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.