18 Useful Python Tricks for Everyday Coding
This article presents eighteen practical Python tricks, covering input handling, conditional checks, parity testing, variable swapping, palindrome detection, list comprehensions, argument packing, dictionary merging, sorting, pretty printing, and list reversal, each illustrated with clear bad‑practice and improved code examples.
Handling Multiple User Inputs
Sometimes we need to obtain several inputs from the user; a typical approach is to call input() multiple times and store each result in a separate variable.
# bad practice
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n3 = input("enter a number : ")
print(n1, n2, n3)A better method is to read a single line, split it, and assign the values at once.
# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)Handling Multiple Conditional Statements
When a program needs to evaluate several conditions, the built‑in all() and any() functions can simplify the logic.
Use all() for multiple and conditions and any() for multiple or conditions.
Example using all() (bad practice):
# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to but the product.")Improved version with all():
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if all(conditions):
print("Yes, I want to but the product.")Example using any() (bad practice):
# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to but the product.")Improved version with any():
# 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
Convert the user input to an integer and check the remainder when divided by 2; a zero remainder indicates an even number.
print('odd' if int(input('Enter a number: ')) % 2 else 'even')Swapping Variables
Python allows swapping values without a temporary variable by using tuple unpacking.
# bad practice
v1 = 100
v2 = 200
temp = v1
v1 = v2
v2 = tempBetter approach:
# good practice
v1 = 100
v2 = 200
v1, v2 = v2, v1Checking If a String Is a Palindrome
The simplest way to reverse a string is using slicing [::-1]. print("John Deo"[::-1]) To test for a palindrome, compare the string with its reversed version.
v1 = "madam" # is a palindrome string
v2 = "master" # is not a palindrome string
print(v1.find(v1[::-1]) == 0) # True
print(v2.find(v2[::-1]) == 0) # FalseUsing Inline If Statements
When a condition leads to a single statement, an inline if expression makes the code more concise.
# bad practice
name = "ali"
age = 22
if name:
print(name)
if name and age > 18:
print("user is verified")Better approach:
# a better approach
print(name if name else "")
# good practice
name and print(name)
age > 18 and name and print("user is verified")Removing Duplicate Elements from a List
Convert the list to a set to eliminate duplicates, then back to a list.
lst = [1,2,3,4,3,4,4,5,6,3,1,6,7,9,4,0]
print(lst)
unique_lst = list(set(lst))
print(unique_lst)Finding the Most Repeated Element in a List
Use max() with list.count as the key function.
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
List comprehensions provide a concise way to create new lists.
numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 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)Passing Multiple Arguments with *args
Define a function that accepts a variable number of positional arguments using *args.
def sum_of_squares(n1, n2):
return n1**2 + n2**2
print(sum_of_squares(2, 3)) # output: 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 Indexes
Use enumerate() to obtain both the index and the item while looping.
lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)Joining Multiple List Elements
Use the join() method to concatenate list elements with a separator.
names = ["john", "sara", "jim", "rock"]
print(", ".join(names))Merging Two Dictionaries
Combine dictionaries using the unpacking syntax {**d1, **d2}.
d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)Creating a Dictionary from Two Lists
Use zip() to pair keys and values, then convert to a dictionary.
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))Sorting a Dictionary by Value
Use sorted() with a lambda or itemgetter to sort by values.
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), reverse=True))
print(sorted_d)Pretty Print
Use the pprint module to format complex data structures for readability.
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)Reversing a List
Two common ways to reverse a list are slicing ( mylist[::-1]) and the in‑place reverse() method; the latter is faster.
# using slicing
python -m timeit -n 1000000 -s 'import numpy as np; mylist=list(np.arange(0, 200))' 'mylist[::-1]'
# using reverse()
python -m timeit -n 1000000 -s 'import numpy as np; mylist=list(np.arange(0, 200))' 'mylist.reverse()'Results show that reverse() is noticeably faster than slicing.
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.
