Fundamentals 13 min read

30 Minimal Python Tasks and Code Snippets for Beginners

This article presents 30 concise Python tasks, each demonstrating a specific technique such as duplicate detection, memory usage, string manipulation, list chunking, dictionary merging, and more, allowing beginners to practice and developers to discover useful code patterns.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
30 Minimal Python Tasks and Code Snippets for Beginners

This article collects thirty compact Python exercises that illustrate common programming techniques. Each task includes a brief description and a ready‑to‑run code snippet, making it useful for beginners who want hands‑on practice and for experienced developers looking for quick reference solutions.

1. Duplicate element detection

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

2. Anagram (character composition) check

from collections import Counter

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

print(anagram("abcd3", "3acdb"))  # True

3. Memory size of a variable

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

print(byte_size(''))          # 0
print(byte_size('Hello World'))  # 11

5. Print a string N times without a loop

n = 2
s = "Programming"
print(s * n)  # ProgrammingProgramming

6. Capitalize the 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))))

print(chunk([1,2,3,4,5], 2))  # [[1, 2], [3, 4], [5]]

8. Remove falsy values from a list

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 into separate tuples

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

10. Chain comparisons in a single expression

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

11. Join list elements with commas

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

12. Count vowels 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'))     # 0

13. Decapitalize the first character of a string

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

print(decapitalize('FooBar'))  # fooBar

14. Recursively 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 isinstance(x, list) else x, lst))))
    return result

print(deep_flatten([1, [2], [[3], 4], 5]))  # [1, 2, 3, 4, 5]

15. List difference (elements in A not in B)

def difference(a, b):
    return list(set(a) - set(b))

print(difference([1,2,3], [1,2,4]))  # [3]

16. Difference by applying a function

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]

from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor))  # [1.2]

17. Conditional function call in one 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))  # 9

18. Check for duplicates in a list

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

19. Merge two dictionaries (Python 3.5+)

def merge_dictionaries(a, b):
    return {**a, **b}

a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_dictionaries(a, b))  # {'x': 1, 'y': 3, 'z': 4}

20. Convert two parallel lists into 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}

21. Enumerate list with index and value

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

22. Measure execution time of a code block

import time
start_time = time.time()
# ... code to measure ...
a, b = 1, 2
c = a + b
print(c)  # 3
end_time = time.time()
print("Time:", end_time - start_time)

23. Use try/except with an else clause

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

24. Find the most frequent element 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))  # 2

25. Palindrome check (ignoring non‑letters)

import re

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

print(palindrome('taco cat'))  # True

26. Operator‑based calculator without if‑else

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

27. Shuffle a list using 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

foo = [1,2,3]
print(shuffle(foo))  # e.g., [2,3,1]

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 compact examples cover a wide range of everyday Python tasks, from basic data handling to small algorithmic utilities, providing a practical toolbox for learners and developers alike.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData StructuresAlgorithmsCoding Exercises
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

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.