30 Helpful Python Snippets You Can Learn in 30 Seconds
This article presents thirty concise Python code snippets covering common tasks such as duplicate detection, list chunking, dictionary merging, string manipulation, timing, and functional tricks, offering quick, practical examples for beginners and developers to enhance their coding skills.
The article introduces a collection of thirty short Python snippets designed to help learners practice real‑world tasks quickly, each accompanied by a brief explanation.
1. Duplicate element detection : def all_unique(lst): return len(lst) == len(set(lst)) returns False for a list with repeats and True otherwise.
2. Anagram check : from collections import Counter def anagram(first, second): return Counter(first) == Counter(second) verifies whether two strings contain the same characters.
3. Memory size of an integer : import sys variable = 30 print(sys.getsizeof(variable)) # 24
4. Byte size of a string : def byte_size(string): return len(string.encode('utf-8')) byte_size('Hello World') # 11
5. Print a string N times without a loop : n = 2 s = "Programming" print(s * n) # ProgrammingProgramming
6. Capitalize first letter of each word : s = "programming is awesome" print(s.title()) # Programming Is Awesome
7. Chunk a list into fixed‑size pieces : 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. Remove falsy values : def compact(lst): return list(filter(bool, lst)) compact([0,1,False,2,'',3,'a','s',34]) # [1,2,3,'a','s',34]
9. Unzip a list of pairs : array = [['a','b'],['c','d'],['e','f']] transposed = zip(*array) print(list(transposed)) # [('a','c','e'),('b','d','f')]
10. List difference : def difference(a, b): set_a, set_b = set(a), set(b) return list(set_a.difference(set_b)) difference([1,2,3], [1,2,4]) # [3]
11. Difference by applying a function : def difference_by(a, b, fn): b = set(map(fn, b)) return [item for item in a if fn(item) not in b] difference_by([2.1,1.2], [2.3,3.4], floor) # [1.2]
12. Chained comparison : a = 3 print(2 < a < 8) # True print(1 == a < 2) # False
13. Join list elements with commas : hobbies = ["basketball","football","swimming"] print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
14. Count vowels using regex : import re def count_vowels(s): return len(re.findall(r'[aeiou]', s, re.IGNORECASE)) count_vowels('foobar') # 3
15. Lowercase first character : def decapitalize(string): return string[:1].lower() + string[1:] decapitalize('FooBar') # 'fooBar'
16. Flatten a nested 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]
17. List elements not present in another list : def difference(a, b): return list(set(a).difference(set(b))) difference([1,2,3], [1,2,4]) # [3]
18. Find most frequent element : def most_frequent(lst): return max(set(lst), key=lst.count) most_frequent([1,2,1,2,3,2,1,4,2]) # 2
19. Palindrome check : import re def palindrome(string): s = re.sub(r'[\W_]', '', string.lower()) return s == s[::-1] palindrome('taco cat') # True
20. Operator dictionary for arithmetic without if‑else : import operator action = {"+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul, "**": pow} print(action['-'](50, 25)) # 25
21. Shuffle a list (Fisher‑Yates) : 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 shuffle([1,2,3]) # e.g., [2,3,1]
22. Measure execution time : import time start = time.time() # code to measure end = time.time() print('Time:', end - start)
23. Try/except with else clause : try: 2 * 3 except TypeError: print('An exception was raised') else: print('Thank God, no exceptions were raised.')
24. Most common element (frequency) : def most_frequent(lst): return max(set(lst), key=lst.count)
25. Convert two lists to 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}
26. Enumerate list with index : lst = ["a","b","c","d"] for index, element in enumerate(lst): print("Value", element, "Index", index)
27. Measure code execution time : (see snippet 22).
28. Swap two variables without a temporary variable : def swap(a, b): return b, a a, b = -1, 14 print(swap(a, b)) # (14, -1)
29. Dictionary get with default value : d = {'a': 1, 'b': 2} print(d.get('c', 3)) # 3
These snippets provide quick, ready‑to‑use solutions for everyday Python programming challenges, making them valuable for both learning and rapid development.
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.