30 Essential Python Tricks to Boost Your Coding Skills
This article presents thirty concise Python tasks and code snippets that demonstrate practical techniques—from checking duplicates and measuring memory usage to manipulating strings, lists, dictionaries, and control flow—offering beginners and seasoned developers quick, hands‑on examples to deepen their understanding of core language features.
Learning Python quickly comes from hands‑on mini‑projects; the following thirty minimal tasks provide practical examples for beginners and useful snippets for experienced developers.
1. Duplicate element detection
Checks whether a list contains duplicate elements by comparing its length to the length of a set built from the list.
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True2. Anagram (character composition) check
Determines whether two strings consist of the same characters using collections.Counter.
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True3. Memory size of a variable
Uses sys.getsizeof to report the memory consumption of an integer.
import sys
variable = 30
print(sys.getsizeof(variable)) # 244. Byte size of a string
Returns the number of bytes a UTF‑8 encoded string occupies.
def byte_size(string):
return len(string.encode('utf-8'))
byte_size('') # 0
byte_size('Hello World') # 115. Print a string N times without a loop
Leverages Python’s string multiplication to repeat a string.
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming6. Capitalize the first letter of each word
Uses the title() method to title‑case a sentence.
s = "programming is awesome"
print(s.title()) # Programming Is Awesome7. Chunk a list into fixed‑size pieces
Splits a list into sub‑lists of a given size using ceil and map.
from math import ceil
def chunk(lst, size):
return list(map(lambda x: lst[x*size:x*size+size], range(0, ceil(len(lst)/size))))
chunk([1,2,3,4,5], 2) # [[1, 2], [3, 4], [5]]8. Compact a list by removing falsy values
Filters out False, None, 0, empty strings, etc., using filter(bool, …).
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [1, 2, 3, 'a', 's', 34]9. Unpack paired lists into separate tuples
Uses zip(*array) to transpose a list of pairs.
array = [['a','b'], ['c','d'], ['e','f']]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]10. Chain comparisons in a single expression
Shows how Python can compare multiple values without repeating variables.
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False11. Join a list with commas
Concatenates list elements into a single string separated by commas.
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming12. Count vowels using a regular expression
Counts occurrences of a, e, i, o, u (case‑insensitive) in a string.
import re
def count_vowels(s):
return len(re.findall(r'[aeiou]', s, re.IGNORECASE))
count_vowels('foobar') # 3
count_vowels('gym') # 013. Decapitalize the first character
Ensures the first character of a string is lower‑case while leaving the rest unchanged.
def decapitalize(string):
return string[:1].lower() + string[1:]
decapitalize('FooBar') # 'fooBar'14. Flatten a nested list (shallow)
Recursively expands one level of nesting into a flat list.
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]15. List difference
Returns elements present in the first list but not in the second.
def difference(a, b):
set_a = set(a)
set_b = set(b)
return list(set_a.difference(set_b))
difference([1,2,3], [1,2,4]) # [3]16. Difference by applying a function
Applies a function to the second list before computing the difference.
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]17. Chain function calls in one line
Demonstrates conditional selection of a function and immediate invocation.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 918. Check for duplicates in a list
Returns True if a list contains any repeated elements.
def has_duplicates(lst):
return len(lst) != len(set(lst))
has_duplicates([1,2,3,4,5,5]) # True
has_duplicates([1,2,3,4,5]) # False19. Merge two dictionaries (Python 3.5+)
Shows two ways to combine dictionaries: using dict.update and the unpacking operator **.
def merge_two_dicts(a, b):
c = a.copy()
c.update(b)
return c
a = {'x':1, 'y':2}
b = {'y':3, 'z':4}
print(merge_two_dicts(a, b)) # {'x': 1, 'y': 3, 'z': 4}
# Using dictionary unpacking (Python 3.5+)
def merge_dictionaries(a, b):
return {**a, **b}
print(merge_dictionaries(a, b)) # {'x': 1, 'y': 3, 'z': 4}20. Convert two lists into a dictionary
Pairs keys and values with zip and builds a dictionary.
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'b': 3, 'c': 4}21. Enumerate a list with index
Uses enumerate to access both index and element while iterating.
lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
print("Value", element, "Index", index)
# Value a Index 0
# Value b Index 1
# Value c Index 2
# Value d Index 322. Measure execution time of a code block
Records start and end timestamps with time.time() and computes the elapsed time.
import time
start_time = time.time()
# Example computation
c = 1 + 2
print(c) # 3
end_time = time.time()
print("Time:", end_time - start_time)23. try … else clause
Executes the else block only when no exception is raised.
try:
2 * 3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
# Thank God, no exceptions were raised.24. Most frequent element in a list
Finds the element that appears most often using max with list.count.
def most_frequent(lst):
return max(set(lst), key=lst.count)
lst = [1,2,1,2,3,2,1,4,2]
print(most_frequent(lst)) # 225. Palindrome check
Normalizes a string by removing non‑alphanumeric characters and comparing it to its reverse.
def palindrome(string):
from re import sub
s = sub(r'[\W_]', '', string.lower())
return s == s[::-1]
print(palindrome('taco cat')) # True26. Arithmetic without if‑else using a dictionary
Maps operator symbols to functions from the operator module.
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow,
}
print(action['-'](50, 25)) # 2527. Shuffle a list (Fisher‑Yates)
Creates a new list with elements randomly reordered.
from copy import deepcopy
from random import randint
def shuffle(lst):
temp = deepcopy(lst)
m = len(temp)
while m:
m -= 1
i = randint(0, m)
temp[m], temp[i] = temp[i], temp[m]
return temp
print(shuffle([1,2,3])) # e.g., [2, 3, 1]28. Fully flatten a nested list
Recursively expands all sub‑lists into a single flat list.
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
print(spread([1,2,3,[4,5,6],[7],8,9])) # [1,2,3,4,5,6,7,8,9]29. Swap two values without a temporary variable
Returns the values in reversed order.
def swap(a, b):
return b, a
a, b = -1, 14
print(swap(a, b)) # (14, -1)30. Dictionary get with default value
Uses dict.get(key, default) to provide a fallback when the key is missing.
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3Original source: http://dwz.date/bYre – Author: Fatos Morina
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
