30 Helpful Python Snippets You Can Learn in 30 Seconds or Less
This article presents thirty concise Python code snippets that demonstrate common programming tasks such as checking duplicates, counting vowels, merging dictionaries, measuring execution time, and performing list manipulations, each explained with clear examples for quick learning.
This article presents thirty concise Python code snippets that demonstrate common programming tasks, each accompanied by a brief explanation and example usage.
1. Duplicate Element Check
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 Check
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
print(anagram("abcd3", "3acdb")) # True3. Memory Size of Variable
import sys
variable = 30
print(sys.getsizeof(variable)) # 244. Byte Size of String
def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size('')) # 0
print(byte_size('Hello World')) # 115. Print String N Times
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming6. Capitalize First Letter of Each Word
s = "programming is awesome"
print(s.title()) # Programming Is Awesome7. Chunk List into Fixed Size
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 List (Remove Falsy Values)
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. Unpack Paired List
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]10. Chain Comparison
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False11. Join List with Commas
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming12. Count Vowels
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 First Character
def decapitalize(string):
return string[:1].lower() + string[1:]
print(decapitalize('FooBar')) # fooBar14. Deep Flatten 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 = []
for item in lst:
if isinstance(item, list):
result.extend(deep_flatten(item))
else:
result.append(item)
return result
print(deep_flatten([1, [2], [[3], 4], 5])) # [1, 2, 3, 4, 5]15. List Difference
def difference(a, b):
return list(set(a) - set(b))
print(difference([1,2,3], [1,2,4])) # [3]16. Difference by Function
def difference_by(a, b, fn):
b_mapped = set(map(fn, b))
return [item for item in a if fn(item) not in b_mapped]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor)) # [1.2]17. Chain Function Call
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
def has_duplicates(lst):
return len(lst) != len(set(lst))
print(has_duplicates([1,2,3,4,5,5])) # True
print(has_duplicates([1,2,3,4,5])) # False19. Merge Two Dictionaries
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}20. Convert Two Lists to 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 List
lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
print("Value", element, "Index", index)22. Measure Execution Time
import time
start_time = time.time()
# code to measure
end_time = time.time()
print("Time:", end_time - start_time)23. Try/Except with Else
try:
2 * 3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")24. Most Frequent Element
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
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
print(palindrome('taco cat')) # True26. Operator Dictionary for Arithmetic
import operator
action = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "**": pow}
print(action['-'](50, 25)) # 2527. Shuffle 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
print(shuffle([1,2,3]))28. Expand List Including Sublists
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
def swap(a, b):
return b, a
a, b = -1, 14
print(swap(a, b)) # (14, -1)30. Dictionary Get with Default
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3These snippets provide quick, reusable solutions for everyday Python programming challenges.
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.
