30 Python Tricks You Can Master in 30 Seconds
This article showcases thirty concise Python code snippets—each explainable in half a minute—that help you quickly solve everyday tasks such as checking list uniqueness, detecting anagrams, measuring memory usage, handling strings, manipulating collections, and more.
Many people use Python in data science, machine learning, web development, scripting, and automation because it is simple and powerful.
The following thirty short code snippets can be understood in about thirty seconds each.
1. Uniqueness
Check whether a list contains duplicate elements by comparing its length to the length of a set.
<code>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)) # True</code>2. Anagram
Determine if two strings are anagrams using collections.Counter .
<code>from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
print(anagram("abcd3", "3acdb")) # True</code>3. Memory size
Print the memory size of an object with sys.getsizeof .
<code>import sys
variable = 30
print(sys.getsizeof(variable)) # 24</code>4. Byte size
Return the byte length of a string encoded in UTF‑8.
<code>def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size('😀')) # 4
print(byte_size('Hello World')) # 11</code>5. Print string N times
Print a string multiple times without an explicit loop.
<code>n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming</code>6. Capitalize first letters
Capitalize the first letter of each word using title() .
<code>s = "programming is awesome"
print(s.title()) # Programming Is Awesome</code>7. Chunk list
Split a list into sub‑lists of a given size.
<code>def chunk(lst, size):
return [lst[i:i+size] for i in range(0, len(lst), size)]</code>8. Compact
Remove falsy values (False, None, 0, "") from a list using filter(bool, …) .
<code>def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, 2, '', 3, 'a', 's', 34])) # [1, 2, 3, 'a', 's', 34]</code>9. Transpose array
Transpose a 2‑D list with zip(*array) .
<code>array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]</code>10. Chained comparison
Perform multiple comparisons in a single expression.
<code>a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False</code>11. Join with commas
Join a list of strings into a single comma‑separated string.
<code>hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming</code>12. Count vowels
Count the number of vowels in a string using a regular expression.
<code>import re
def count_vowels(s):
return len(re.findall(r'[aeiou]', s, re.IGNORECASE))
print(count_vowels('foobar')) # 3
print(count_vowels('gym')) # 0</code>13. Decapitalize
Make the first character of a string lowercase.
<code>def decapitalize(s):
return s[:1].lower() + s[1:]
print(decapitalize('FooBar')) # fooBar</code>14. Flatten list (recursive)
Recursively flatten nested lists.
<code>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([deep_flatten(x) if isinstance(x, list) else x for x in lst])
)
return result
print(deep_flatten([1, [2], [[3], 4], 5])) # [1, 2, 3, 4, 5]</code>15. Difference
Return elements present in the first iterable but not in the second.
<code>def difference(a, b):
return list(set(a).difference(set(b)))
print(difference([1,2,3], [1,2,4])) # [3]</code>16. Difference by function
Find items in a whose transformed value (via fn ) is not present in b .
<code>def difference_by(a, b, fn):
b_set = set(map(fn, b))
return [item for item in a if fn(item) not in b_set]
print(difference_by([2.1, 1.2], [2.3, 3.4], floor)) # [1.2]
print(difference_by([{'x':2}, {'x':1}], [{'x':1}], lambda v: v['x'])) # [{'x':2}]</code>17. Conditional function call
Choose between two functions in a single line.
<code>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)) # 9</code>18. Duplicate detection
Check if a list contains duplicates using set length comparison.
<code>def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False</code>19. Merge dictionaries
Combine two dictionaries, with values from the second overriding the first.
<code>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}</code>20. Merge dictionaries (Python 3.5+)
<code>def merge_dictionaries(a, b):
return {**a, **b}
print(merge_dictionaries(a, b)) # {'x': 1, 'y': 3, 'z': 4}</code>21. List to dictionary
Convert two parallel lists into a dictionary using zip .
<code>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}</code>22. Enumerate
Iterate over a list while obtaining both index and value.
<code>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 3</code>23. Most frequent element
Return the element that appears most often in a list.
<code>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)) # 2</code>24. Palindrome check
Check whether a string reads the same forwards and backwards, ignoring case and non‑alphanumeric characters.
<code>def palindrome(s):
from re import sub
cleaned = sub(r'[\W_]', '', s.lower())
return cleaned == cleaned[::-1]
print(palindrome('taco cat')) # True</code>25. Operator‑based calculator (no if‑else)
Perform arithmetic operations by mapping symbols to functions from operator .
<code>import operator
actions = {
'+': operator.add,
'-': operator.sub,
'/': operator.truediv,
'*': operator.mul,
'**': pow,
}
print(actions['-'](50, 25)) # 25</code>26. Fisher‑Yates shuffle
Randomly reorder a list in‑place.
<code>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
foo = [1,2,3]
print(shuffle(foo)) # e.g., [2,3,1]</code>27. Spread (list concatenation)
Mimic JavaScript’s [...arr] by flattening one level of nesting.
<code>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]</code>28. Swap variables
Swap two values without a temporary variable.
<code>def swap(a, b):
return b, a
a, b = -1, 14
print(swap(a, b)) # (14, -1)</code>29. Get default for missing key
Retrieve a default value when a key is absent from a dictionary.
<code>d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3</code>30. Time a code block
Measure execution time of a small piece of code.
<code>import time
start = time.time()
# example code
c = 1 + 2
print(c) # 3
end = time.time()
print("Time:", end - start)
# Time: 0.00001 (example)</code>All snippets are sourced from the 30‑seconds‑of‑knowledge repository, which contains many more useful examples for Python and other languages.
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.