Boost Your Python Skills: 20 Essential Tricks Every Developer Should Know
This article presents a curated collection of practical Python tricks—from handling multiple user inputs and using all/any for condition checks, to swapping variables, detecting palindromes, removing duplicates, finding the most frequent list item, leveraging list comprehensions, *args, enumerate, string joining, dictionary merging, sorting, pretty‑printing, and comparing list‑reversal methods—each illustrated with clear code examples.
Handling Multiple User Inputs
Instead of calling input() repeatedly, you can read all values at once and split them:
# good practice
n1, n2, n3 = input("enter numbers: ").split()
print(n1, n2, n3)Using all() and any() for Multiple Conditions
Combine several and conditions with all() and several or conditions with any() for clearer code.
# good practice for all()
conditions = [size == "lg", color == "blue", price < 100]
if all(conditions):
print("Yes, I want to buy the product.")
# good practice for any()
if any(conditions):
print("Yes, I want to buy the product.")Checking Number Parity
Use a one‑liner to print "odd" or "even" based on the remainder of division by 2:
print('odd' if int(input('Enter a number: ')) % 2 else 'even')Swapping Variables Without a Temporary Variable
# good practice
v1, v2 = v2, v1Detecting Palindromes
Compare a string with its reverse using slicing:
v1 = "madam"
print(v1.find(v1[::-1]) == 0) # TrueRemoving Duplicate Elements from a List
lst = [1, 2, 3, 4, 3, 4, 5]
unique_lst = list(set(lst))
print(unique_lst)Finding the Most Repeated Element
most_repeated_item = max(lst, key=lst.count)
print(most_repeated_item)List Comprehensions
Create concise, readable lists in a single expression:
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 Variable Numbers of Arguments
def sum_of_squares(*args):
return sum(item**2 for item in args)
print(sum_of_squares(2, 3, 4)) # 29
print(sum_of_squares(2, 3, 4, 5, 6)) # 90Iterating with Indexes
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}
merged = {**d1, **d2}
print(merged) # {'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
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
# or using itemgetter
from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
# descending order
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))Pretty‑Printing Complex Structures
from pprint import pprint
data = {"name": "john deo", "age": "22", "address": {"country": "canada", "state": "...", "address": "street st.34"}, "attr": {"verified": True}}
print(data)
pprint(data)Reversing a List – Slice vs reverse()
Both methods work, but list.reverse() is faster:
# slice (creates a new list)
reversed_list = mylist[::-1]
# in‑place reversal
mylist.reverse()Author: Anonymous Source: Python Developer Community
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
