Fundamentals 15 min read

30 Essential Python Mini‑Tasks and Code Snippets for Beginners

This article presents a curated collection of thirty practical Python mini‑tasks, each accompanied by concise explanations and ready‑to‑run code snippets that illustrate common operations such as duplicate detection, anagram checking, memory usage, dictionary merging, and more, helping beginners quickly master useful programming techniques.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
30 Essential Python Mini‑Tasks and Code Snippets for Beginners

Learning Python efficiently involves hands‑on practice with small, focused projects. Below are thirty concise tasks that demonstrate useful patterns and idioms for everyday Python programming.

1. Duplicate Element Detection

The following function checks whether a list contains duplicate elements by comparing its length with the length of a set created from it.

<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. Character Composition (Anagram) Check

Using collections.Counter to verify whether two strings consist of the same characters.

<code>from collections import Counter

def anagram(first, second):
    return Counter(first) == Counter(second)

print(anagram("abcd3", "3acdb"))  # True</code>

3. Memory Size

Shows how to obtain the memory footprint of a variable with sys.getsizeof .

<code>import sys
variable = 30
print(sys.getsizeof(variable))  # 24</code>

4. Byte Size of a String

Calculates the number of bytes a string occupies when encoded in UTF‑8.

<code>def byte_size(string):
    return len(string.encode('utf-8'))

print(byte_size(''))        # 0
print(byte_size('Hello World'))  # 11</code>

5. Print a String N Times

Repeats a string without an explicit loop.

<code>n = 2
s = "Programming"
print(s * n)  # ProgrammingProgramming</code>

6. Capitalize First Letter of Each Word

Uses the title() method.

<code>s = "programming is awesome"
print(s.title())  # Programming Is Awesome</code>

7. Chunk a List

Splits a list into sub‑lists of a given size.

<code>from math import ceil

def chunk(lst, size):
    return list(map(lambda x: lst[x*size:x*size+size], list(range(0, ceil(len(lst)/size)))) )

print(chunk([1,2,3,4,5], 2))  # [[1,2],[3,4],[5]]</code>

8. Compact (Remove Falsy Values)

Filters out False , None , 0 , empty strings, etc.

<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. Unpack Paired Lists

Transposes a list of pairs using zip and the splat operator.

<code>array = [['a','b'], ['c','d'], ['e','f']]
transposed = zip(*array)
print(list(transposed))  # [('a','c','e'), ('b','d','f')]</code>

10. Chained Comparison

Demonstrates Python's ability to compare multiple values in a single expression.

<code>a = 3
print(2 < a < 8)   # True
print(1 == a < 2)  # False</code>

11. Comma‑Separated Join

Joins list elements into a single string separated by commas.

<code>hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming</code>

12. Vowel Count

Counts 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 First Character

Forces the first character of a string to lower case.

<code>def decapitalize(string):
    return string[:1].lower() + string[1:]

print(decapitalize('FooBar'))  # fooBar</code>

14. Deep Flatten a List

Recursively flattens 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(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]
</code>

15. List Difference

Returns elements present in the first list but not in the second.

<code>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]
</code>

16. Difference by Function

Applies a function to elements before computing the difference.

<code>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]
</code>

17. Chain Function Calls

Shows conditional function selection 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. Check for Duplicates

Returns True if a list contains duplicate elements.

<code>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]))    # False
</code>

19. Merge Two Dictionaries

Creates a new dictionary by copying the first and updating it with the second.

<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. Convert Two Lists to a Dictionary

Uses zip to pair keys and values.

<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>

21. Enumerate a List

Iterates over a list while accessing both index and element.

<code>lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
    print("Value", element, "Index", index)
</code>

22. Measure Execution Time

Uses time.time() to compute how long a block of code takes.

<code>import time
start_time = time.time()
# ... code ...
end_time = time.time()
print("Time:", end_time - start_time)
</code>

23. Try‑Else Block

Executes the else clause when no exception is raised.

<code>try:
    2 * 3
except TypeError:
    print("An exception was raised")
else:
    print("Thank God, no exceptions were raised.")
</code>

24. Most Frequent Element

Finds the element that appears most often in a list.

<code>def most_frequent(lst):
    return max(set(lst), key=lst.count)

print(most_frequent([1,2,1,2,3,2,1,4,2]))  # 2
</code>

25. Palindrome Check

Determines whether a string is a palindrome, ignoring case and non‑alphanumeric characters.

<code>import re

def palindrome(string):
    s = re.sub(r'[\W_]', '', string.lower())
    return s == s[::-1]

print(palindrome('taco cat'))  # True
</code>

26. Operator‑Based Calculator Without If‑Else

Maps arithmetic symbols to functions from the operator module.

<code>import operator
action = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    '**': pow,
}
print(action['-'](50, 25))  # 25
</code>

27. Shuffle a List (Fisher‑Yates)

Creates a new shuffled list using the Fisher‑Yates algorithm.

<code>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]))
</code>

28. Flatten List (Alternative Implementation)

Another version of list flattening that handles nested lists.

<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>

29. Swap Two Values

Swaps variables without a temporary placeholder.

<code>def swap(a, b):
    return b, a

a, b = -1, 14
print(swap(a, b))  # (14, -1)
</code>

30. Dictionary Default Value

Uses dict.get() to provide a default when a key is missing.

<code>d = {'a': 1, 'b': 2}
print(d.get('c', 3))  # 3
</code>

These snippets collectively form a practical toolbox for Python beginners, covering data validation, collection manipulation, algorithmic patterns, and common language features.

PythonprogrammingData StructuresAlgorithmstutorialcode snippets
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.