Fundamentals 16 min read

25 Essential Python Tricks for Efficient Coding

This article compiles twenty‑five practical Python tricks—including in‑place swapping, chained comparisons, ternary expressions, multi‑line strings, membership tests, various ways to reverse sequences, simultaneous variable initialization, module path printing, dictionary comprehensions, string concatenation, enumeration, multiple return values, simple HTTP servers, debugging with pdb, advanced use of else, exception handling, introspection, container types, map, reduce, split, filter, and sorted—each illustrated with concise code examples to boost productivity and code readability.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
25 Essential Python Tricks for Efficient Coding

This article presents a curated list of twenty‑five Python idioms that improve code brevity and performance.

1. In‑place swapping

Python allows simultaneous assignment to swap values without a temporary variable.

x, y = 10, 20
print(x, y)

x, y = y, x
print(x, y)

2. Chained comparisons

Multiple relational checks can be combined in a single expression.

n = 10
result = 1 < n < 20
print(result)  # True
result = 1 > n <= 9
print(result)  # False

3. Ternary operator

Use value_if_true if condition else value_if_false for concise conditional assignments. x = 10 if (y == 9) else 20 It also works inside comprehensions and class instantiation.

[m**2 if m > 10 else m**4 for m in range(50)]

def small(a, b, c):
    return a if a <= b and a <= c else (b if b <= a and b <= c else c)

x = (classA if y == 1 else classB)(param1, param2)

4. Multi‑line strings

Triple quotes simplify multi‑line literals compared to escaped newlines in C.

a = '''dvfssd
fsdfdsfsd
dsdsfbfdfasf
afasfaf'''
print(a)

5. Membership test

Use in to check if an element exists in a collection.

if m in [1,3,5,7]:
    print('found')

# instead of multiple equality checks

6. Four ways to reverse sequences

Reverse a list in place, iterate over a reversed view, slice a string, or slice a list.

testList = [1,3,5]
testList.reverse()
print(testList)  # [5,3,1]

for element in reversed([1,3,5]):
    print(element)

"Test Python"[::-1]  # 'nohtyP tseT'

[1,3,5][::-1]  # [5,3,1]

7. Simultaneous variable initialization

Assign multiple variables in one statement or unpack a list.

a,b,c,d = 1,2,3,4

lst = [1,2,3]
x,y,z = lst
print(x, y, z)

8. Print module path

import socket
print(socket)  # <module 'socket' from '/usr/lib/python2.7/socket.py'>

9. Dictionary and set comprehensions

testDict = {i: i*i for i in range(10)}
testSet = {i*2 for i in range(10)}
print(testSet)
print(testDict)

10. String concatenation

a = "i "
b = "love "
c = "you"
print(a+b+c)

lst = ['a','b','c']
print(''.join(lst))

11. Enumerate with index

lst = [10,20,30]
for i, value in enumerate(lst):
    print(i, ': ', value)

12. Return multiple values

def a():
    return 1,2,3,4,5

13. Quick HTTP file server python3 -m http.server 14. Debugging with pdb

import pdb
pdb.set_trace()

15. Direct iteration over sequences

l = [0,1,2,3,4,5]
for i in l:
    print(i)  # faster than indexing

16. Effective use of else in loops and try

In for / while loops, else runs only when the loop isn’t terminated by break. In try, else runs only if no exception occurs.

for i in l:
    if i == 6:
        break
else:
    print('completed')

try:
    a()
except OSError:
    pass
else:
    print('no error')

17. Exception handling syntax

try:
    risky()
except OSError:
    handle_os()
except (ValueError, TypeError) as e:
    handle_specific(e)
else:
    print('no exception')
finally:
    cleanup()

18. Introspection

Functions like type(), dir(), getattr(), hasattr(), and isinstance() reveal object information at runtime.

19. Container overview

Lists (mutable, ordered), tuples (immutable, ordered, hashable), sets (unordered, unique), and dictionaries (unordered key‑value mapping).

20. map() function

def f(x):
    return x*x
r = map(f, [1,2,3,4,5,6,7,8,9])
print(list(r))

print(list(map(str, [1,2,3,4,5,6,7,8,9])))

21. reduce() function

from functools import reduce

def fn(x, y):
    return x*10 + y
print(reduce(fn, [1,3,5,7,9]))  # 13579

# building an int from a string
char_map = {str(i): i for i in range(10)}

def strint(s):
    return reduce(lambda x, y: x*10 + y, map(char_map.get, s))

22. split() method

text = "a b c"
parts = text.split()

23. Theory meets practice

Combine learned tricks to solve typical interview problems, such as reversing word order in a sentence. print(" ".join(input().split()[::-1])) Another example merges two integer arrays, removes duplicates, and sorts them:

a,b,c,d = input(), list(map(int, input().split())), input(), list(map(int, input().split()))
print("".join(map(str, sorted(set(b+d)))))

And removing duplicate digits from a reversed integer:

result = ""
for i in input()[::-1]:
    if i not in result:
        result += i
print(result)

24. filter() function

def is_odd(n):
    return n % 2 == 1
print(list(filter(is_odd, [1,2,4,5,6,9,10,15])))

# Sieve of Eratosthenes using filter

def _odd_iter():
    n = 1
    while True:
        n += 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

25. sorted() function

sorted([36,5,-12,9,-21])
sorted([36,5,-12,9,-21], key=abs)
sorted(['bob','about','Zoo','Credit'])
sorted(['bob','about','Zoo','Credit'], key=str.lower)
sorted(['bob','about','Zoo','Credit'], key=str.lower, reverse=True)

The article continuously updates these fundamental Python techniques to help developers write cleaner, faster, 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.

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