30 Minimal Python Tasks: Handy Code Snippets for Everyday Programming
This article presents thirty concise Python examples covering list deduplication, anagram checking, memory usage, string manipulation, chunking, dictionary merging, timing, exception handling, and many other common tasks, each explained with clear descriptions and ready‑to‑run code snippets for beginners and developers alike.
The article introduces a collection of thirty compact Python tasks designed to help beginners practice real‑world coding patterns while reinforcing core language concepts.
1. Duplicate element detection
This function checks whether a list contains duplicate items 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]
print(all_unique(x)) # False
print(all_unique(y)) # True2. Anagram (character composition) check
Using collections.Counter , this function determines whether two strings consist of the same characters.
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
print(anagram("abcd3", "3acdb")) # True3. Memory size of a variable
Shows how to obtain the memory footprint of an integer using sys.getsizeof .
import sys
variable = 30
print(sys.getsizeof(variable)) # 244. Byte size of a string
Calculates the number of bytes a Unicode string occupies when encoded in UTF‑8.
def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size('😀')) # 4
print(byte_size('Hello World')) # 115. Print a string N times without a loop
Uses string multiplication to repeat a string.
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming6. Capitalize the first letter of each word
Applies the title() method.
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 math.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))))
print(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 , and empty strings.
def compact(lst):
return list(filter(bool, lst))
print(compact([0,1,False,2,'',3,'a','s',34])) # [1, 2, 3, 'a', 's', 34]9. Unzip 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
Demonstrates Python’s ability to compare multiple values in a single expression.
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False11. Join list elements with commas
Creates a single string from a list using ', '.join() .
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming12. Count vowels in a string
Uses a regular expression to count occurrences of a, e, i, o, u.
import re
def count_vowels(s):
return len(re.findall(r'[aeiou]', s, re.IGNORECASE))
print(count_vowels('foobar')) # 3
print(count_vowels('gym')) # 013. Decapitalize the first character
Ensures the first character of a string is lower‑case.
def decapitalize(string):
return string[:1].lower() + string[1:]
print(decapitalize('FooBar')) # fooBar14. Flatten a nested list (shallow)
Recursively expands nested 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
def deep_flatten(lst):
result = []
result.extend(spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
print(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))
print(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
print(difference_by([2.1,1.2], [2.3,3.4], floor)) # [1.2]17. Conditional function call in one line
Selects add or subtract based on a condition.
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
Compares list length to the length of its set.
def has_duplicates(lst):
return len(lst) != len(set(lst))
print(has_duplicates([1,2,3,4,5,5])) # True19. Merge two dictionaries (Python 3.5+)
Shows both the classic copy/update method and the dictionary unpacking syntax.
def merge_two_dicts(a, b):
c = a.copy()
c.update(b)
return c
def merge_dictionaries(a, b):
return {**a, **b}
print(merge_two_dicts({'x':1,'y':2}, {'y':3,'z':4}))
print(merge_dictionaries({'x':1,'y':2}, {'y':3,'z':4}))20. Convert two lists into a dictionary
Uses zip to pair keys and values.
def to_dictionary(keys, values):
return dict(zip(keys, values))
print(to_dictionary(['a','b','c'], [2,3,4])) # {'a': 2, 'b': 3, 'c': 4}21. Enumerate list with index
Iterates over a list while accessing both index and element.
lst = ["a","b","c","d"]
for index, element in enumerate(lst):
print("Value", element, "Index", index)
# Value a Index 0 ...22. Measure execution time
Uses time.time() to compute elapsed time for a code block.
import time
start_time = time.time()
# code to measure
end_time = time.time()
print("Time:", end_time - start_time)23. Try/except with else clause
Runs the else block when no exception occurs.
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 with the highest occurrence count.
def most_frequent(lst):
return max(set(lst), key=lst.count)
print(most_frequent([1,2,1,2,3,2,1,4,2])) # 225. Palindrome check
Normalizes a string and compares 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. Operator dictionary for arithmetic without if‑else
Maps 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 shuffled copy of a list.
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while m:
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
print(shuffle([1,2,3])) # e.g., [2,3,1]28. Flatten a list (alternative implementation)
Same as snippet 14, demonstrating another spread function.
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 variables 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.
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3The article concludes with a thank‑you note and promotional QR codes for a free Python public course, encouraging readers to scan for additional learning resources.
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.