Fundamentals 12 min read

30 Minimal Python Tasks and Code Snippets for Beginners

This article presents thirty concise Python exercises, each with a short description and ready‑to‑run code illustrating common tasks such as duplicate detection, anagram checking, memory and byte size measurement, string repetition, title‑casing, list chunking, filtering, dictionary merging, enumeration, timing, exception handling, frequency analysis, palindrome testing, operator‑based calculations, shuffling, and more.

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

The article provides a collection of thirty minimal Python tasks that serve both beginners learning the language and experienced developers looking for handy one‑liners.

1. Duplicate Element Check

Check whether a list contains duplicate elements using set() to remove duplicates.

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

Determine if two strings consist of the same characters using collections.Counter.

from collections import Counter

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

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

3. Memory Usage

Show the memory size of a variable with sys.getsizeof.

import sys
variable = 30
print(sys.getsizeof(variable))  # 24

4. 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'))  # 11

5. Print a String N Times Without a Loop

Use multiplication of a string to repeat it.

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

6. Capitalize First Letter of Each Word

Apply the title() method.

s = "programming is awesome"
print(s.title())  # Programming Is Awesome

7. List Chunking

Split a list into chunks 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. Compact (Remove Falsy Values)

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

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. Merge Two Dictionaries

Combine dictionaries using copy() and update() or the unpacking syntax.

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}

# Python 3.5+ alternative

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

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

10. Convert Two Lists to a Dictionary

Use zip and dict.

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}

11. Enumerate a List

Iterate with index and value.

lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
    print("Value", element, "Index", index)
# Output:
# Value a Index 0
# Value b Index 1
# Value c Index 2
# Value d Index 3

12. Measure Execution Time

Use time.time() before and after the code block.

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

13. Try/Else Block

Run else when no exception occurs.

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

14. Most Frequent Element

Find the element that appears most often.

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

15. Palindrome Check

Ignore case and non‑alphabetic characters.

import re

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

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

16. Operator‑Based Calculator Without If‑Else

Map symbols to functions in a dictionary.

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

17. Shuffle a List (Fisher‑Yates)

Randomly reorder elements.

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

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

18. Swap Two Variables

Exchange values without a temporary variable.

def swap(a, b):
    return b, a

a, b = -1, 14
print(swap(a, b))  # (14, -1)

19. Dictionary Default Value

Use dict.get with a fallback.

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

The collection covers a broad range of everyday Python operations, offering ready‑to‑copy snippets that illustrate concise, idiomatic solutions.

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.

PythonprogrammingAlgorithmscode 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

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.