Common Python Tricks and Best Practices
This article compiles a series of practical Python tricks—including handling multiple inputs, using all/any for condition checks, swapping variables, checking parity, removing duplicates, merging dictionaries, list comprehensions, *args, enumerate, joining strings, zip, sorting dictionaries, pretty‑printing, and list reversal performance—to help developers write cleaner, more efficient code.
In this article we present a collection of frequently used Python tricks that improve code readability and efficiency.
Handling multiple inputs
# bad practice
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n3 = input("enter a number : ")
print(n1, n2, n3) # good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)Using all() and any() for multiple conditions
# bad practice
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to but the product.") # good practice
conditions = [size == "lg", color == "blue", price < 100]
if all(conditions):
print("Yes, I want to but the product.") # bad practice
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to but the product.") # good practice
conditions = [size == "lg", color == "blue", price < 100]
if any(conditions):
print("Yes, I want to but the product.")Checking odd/even numbers
print('odd' if int(input('Enter a number: ')) % 2 else 'even')Swapping variables
# bad practice
temp = v1
v1 = v2
v2 = temp # good practice
v1, v2 = v2, v1Palindrome test
v1 = "madam" # palindrome
v2 = "master" # not a palindrome
print(v1.find(v1[::-1]) == 0) # True
print(v2.find(v2[::-1]) == 0) # FalseRemoving duplicate elements from a list
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
unique_lst = list(set(lst))
print(unique_lst)Finding the most frequent element in a list
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
most_repeated_item = max(lst, key=lst.count)
print(most_repeated_item)List comprehensions
numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 == 0]
odds = [y for y in numbers if y not in evens]Using *args to accept multiple arguments
def sum_of_squares(*args):
return sum(item**2 for item in args)
print(sum_of_squares(2, 3, 4))
print(sum_of_squares(2, 3, 4, 5, 6))Enumerating with index
lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)Joining list elements into a string
names = ["john", "sara", "jim", "rock"]
print(", ".join(names))Merging dictionaries
d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)Creating a dictionary from two lists using zip
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
print(zipped)Sorting a dictionary by value
d = {"v1": 80, "v2": 20, "v3": 40, "v4": 20, "v5": 10}
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print(sorted_d)Pretty‑printing complex data structures
from pprint import pprint
data = {"name": "john deo", "age": "22", "address": {"country": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"}, "attr": {"verified": True, "emailaddress": True}}
print(data)
pprint(data)Reversing a list – slice vs reverse()
# slice method
mylist[::-1]
# reverse method (in‑place)
mylist.reverse()Benchmarks show that the built‑in reverse() method is faster than slicing, though slicing returns a new list while reverse() modifies the original.
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.
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.
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.
