Essential Python Tricks for Efficient Coding
This article presents a collection of practical Python tricks, covering efficient input handling, condition evaluation with all/any, odd‑even checks, variable swapping, palindrome detection, inline conditional expressions, duplicate removal, frequency analysis, list comprehensions, flexible argument passing, enumeration, string joining, dictionary merging, sorting, and pretty‑printing, each illustrated with clear code examples.
In this article we share a set of commonly used Python tricks that simplify everyday coding tasks.
1. 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) # good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)2. 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 with all()
conditions = [size == "lg", color == "blue", price < 100]
if all(conditions):
print("Yes, I want to but the product.") # good practice with any()
if any(conditions):
print("Yes, I want to but the product.")3. Determining odd or even numbers
print('odd' if int(input('Enter a number: ')) % 2 else 'even')4. Swapping variables without a temporary variable
# bad practice
temp = v1
v1 = v2
v2 = temp # good practice
v1, v2 = v2, v15. Checking if a string is a palindrome
v1 = "madam"
v2 = "master"
print(v1.find(v1[::-1]) == 0) # True
print(v1.find(v2[::-1]) == 0) # False6. Using inline if statements
# better approach
print(name if name else "")
name and print(name)
age > 18 and name and print("user is verified")7. 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)8. Finding the most frequent element in a list
most_repeated_item = max(lst, key=lst.count)
print(most_repeated_item)9. 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]10. Passing multiple arguments with *args
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))11. Getting index while iterating
lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)12. Concatenating list elements with join()
names = ["john", "sara", "jim", "rock"]
print(", ".join(names))13. Merging dictionaries
d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)14. Creating a dictionary from two lists using zip()
keys = ['a','b','c']
vals = [1,2,3]
zipped = dict(zip(keys, vals))
print(zipped)15. 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)Alternatively using itemgetter and reverse=True for descending order.
16. Pretty‑printing complex data structures
from pprint import pprint
data = {"name":"john deo","age":"22","address":{"contry":"canada","state":"an state of canada :)","address":"street st.34 north 12"},"attr":{"verified":True,"emialaddress":True}}
print(data)
pprint(data)These snippets demonstrate concise, readable, and Pythonic ways to solve frequent programming problems.
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.
