Common Python Tricks and Best Practices
This article presents a collection of practical Python tricks covering multiple user inputs, the use of all() and any() for condition handling, odd/even checks, variable swapping, palindrome detection, inline if statements, duplicate removal, finding the most frequent list element, list comprehensions, *args, enumerate, string joining, dictionary merging, sorting, pretty‑printing, and efficient list reversal techniques.
In this article we discuss some of the most frequently used Python tricks. Most of these tricks are simple tricks I have used in daily work and I think good things should be shared with everyone.
Handling multiple user inputs
Sometimes we need to get several inputs from the user. A common (but inefficient) way is:
# bad practice
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n3 = input("enter a number : ")
print(n1, n2, n3)A better approach is to read a single line and split it:
# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)Handling multiple condition statements
When we need to check several conditions we can use all() for logical AND and any() for logical OR. Example with all():
# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to buy the product.")Improved version using a list of conditions:
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if all(conditions):
print("Yes, I want to buy the product.")Similar improvement for any():
# bad practice
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to buy the product.") # good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if any(conditions):
print("Yes, I want to buy the product.")Determining odd or even numbers
print('odd' if int(input('Enter a number: ')) % 2 else 'even')Swapping variables
# bad practice
v1 = 100
v2 = 200
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 "")
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 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]
cities = ['London', 'Dublin', 'Oslo']
def visit(city):
print("Welcome to " + city)
for city in cities:
visit(city)Using *args to pass multiple arguments
def sum_of_squares(n1, n2):
return n1**2 + n2**2
print(sum_of_squares(2,3)) # 13
# dynamic version
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) # {'v1': 22, 'v2': 44, 'v3': 55}Creating a dictionary from two lists
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)
# using itemgetter
from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
print(sorted_d)
# descending order
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
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
# using slicing
mylist[::-1]
# using reverse()
mylist.reverse()
# timing example (slice: 15.6 µs, reverse(): 10.7 µs)Overall, these snippets demonstrate concise, readable, and efficient ways to perform common Python tasks.
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.
