Common Python Tricks and Best Practices
This article presents a collection of practical Python tricks—including handling multiple inputs, using all/any for condition checks, determining odd/even numbers, swapping variables, palindrome detection, inline if statements, removing duplicates, finding the most frequent element, list comprehensions, *args, enumerate, joining strings, merging dictionaries, creating dictionaries with zip, sorting dictionaries, reversing lists efficiently, and pretty‑printing data—each illustrated with clear code examples.
In this article we discuss frequently used Python tricks that the author has collected from daily work and wants to share.
Handling multiple user inputs
# bad practice
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n3 = input("enter a number : ")
print(n1, n2, n3)Better approach using tuple unpacking:
# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)Processing multiple conditional statements
Use all() for multiple AND conditions and any() for multiple OR 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.")Determining odd or 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, v1Checking if a string is a palindrome
v1 = "madam" # palindrome
v2 = "master" # not a palindrome
print(v1.find(v1[::-1]) == 0) # True
print(v2.find(v2[::-1]) == 0) # FalseUsing inline if statements
# bad practice
if name:
print(name)
if name and age > 18:
print("user is verified") # better approach
print(name if name else "")
name and print(name)
age > 18 and name and print("user is verified")Removing 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 repeated 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 pass 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))Iterating with index using enumerate
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))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)Using itemgetter and reverse=True for descending order:
from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))Reversing a list
# slice method (creates new list)
new_list = mylist[::-1]
# reverse() method (in‑place)
mylist.reverse()Performance test shows reverse() is faster than slicing.
Pretty‑printing 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)Using pprint makes dictionary output easier to read.
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.
