30 Quick Python Mini‑Projects to Master Core Programming Skills
This tutorial presents thirty concise Python tasks—ranging from duplicate detection and anagram checking to list chunking, dictionary merging, and execution timing—each accompanied by clear explanations and ready‑to‑run code snippets, enabling beginners to solidify fundamental concepts through hands‑on practice.
Learning Python fastest through hands‑on mini‑projects, this article provides thirty concise tasks that beginners can implement to reinforce core language concepts.
1. Duplicate Element Detection
Check whether a list contains duplicate elements using set().
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. Character Composition (Anagram) Check
Determine if 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 Usage
Show the memory size of an integer variable.
import sys
variable = 30
print(sys.getsizeof(variable)) # 244. Byte Size of a String
Calculate the number of bytes a string occupies when encoded in UTF‑8.
def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size('')) # 0
print(byte_size('Hello World')) # 115. Print a String N Times
Print a string repeatedly without an explicit loop.
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming6. Capitalize First Letter of Each Word
Use title() to capitalize the first letter of every word.
s = "programming is awesome"
print(s.title()) # Programming Is Awesome7. Chunk a List
Split a list into sub‑lists of a given 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. Remove Falsy Values
Filter 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. Unpack Paired Lists
Transpose a list of pairs using zip(*...).
array = [['a','b'], ['c','d'], ['e','f']]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]10. Chain Comparison
Compare a variable against multiple bounds in a single expression.
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False11. Comma Join
Join 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. Vowel Count (Regex)
Count vowels in a string using a regular expression.
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 Letter
Make the first character of a string lowercase.
def decapitalize(string):
return string[:1].lower() + string[1:]
print(decapitalize('FooBar')) # fooBar14. Expand List (One‑Level)
Flatten a list one level deep.
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]15. List Difference
Return elements of the first list that are not present 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 Function
Apply a function to both lists 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. Chain Function Calls
Choose a function to call based on a condition in a single line.
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
Return True if a list contains duplicate items.
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)) # False19. Merge Two Dictionaries
Combine two dictionaries, with the second overriding overlapping keys.
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. Merge Dictionaries with **
Python 3.5+ syntax for merging dictionaries.
def merge_dictionaries(a, b):
return {**a, **b}
print(merge_dictionaries(a, b)) # {'x': 1, 'y': 3, 'z': 4}21. Enumerate List
Iterate over a list while accessing both index and value.
lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
print("Value", element, "Index", index)22. Measure Execution Time
Calculate how long a block of code takes to run.
import time
start_time = time.time()
# ... code to measure ...
end_time = time.time()
print("Time:", end_time - start_time)23. Try/Except with Else
Run an else block only when no exception occurs.
try:
2 * 3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")24. Most Frequent Element
Find the element that appears most often in a list.
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))25. Palindrome Check
Determine whether a string is a palindrome, ignoring case and non‑alphanumeric characters.
def palindrome(string):
from re import sub
s = sub(r'[\W_]', '', string.lower())
return s == s[::-1]
print(palindrome('taco cat')) # True26. Operator Dictionary Calculator
Perform arithmetic operations without explicit if/else by mapping symbols to functions.
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow,
}
print(action['-'](50, 25)) # 2527. Shuffle List (Fisher‑Yates)
Randomly reorder a list in place.
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]))28. Deep Flatten List
Recursively flatten a nested list into a single‑level list.
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]29. Swap Values Without Temporary Variable
Exchange two variables using tuple unpacking.
def swap(a, b):
return b, a
a, b = -1, 14
print(swap(a, b)) # (14, -1)30. Dictionary Default Value
Use dict.get() to retrieve a value with a fallback default.
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3These thirty compact exercises give Python beginners practical exposure to common data‑structure manipulations, algorithmic patterns, and language features, encouraging active coding to retain core concepts.
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.
