Fundamentals 10 min read

30‑Second Python Snippets That Unlock Powerful Programming Tricks

This article presents a collection of concise Python one‑liners—ranging from creating 2‑D lists and clamping numbers to generating Fibonacci sequences and converting strings to snake_case—each explained with clear code examples and practical use cases for everyday programming tasks.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
30‑Second Python Snippets That Unlock Powerful Programming Tricks

30‑Second Python Snippets

Today we share a handful of Python code snippets that can be learned in about 30 seconds. Each snippet demonstrates a useful programming idea, is easy to understand, and can be applied in many contexts.

1. 2D List

Given a width, height, and optional initial value, return a two‑dimensional list.

def initialize_2d_list(w, h, val=None):
    return [[val for x in range(w)] for y in range(h)]

Example:

>> initialize_2d_list(2, 2)
[[None, None], [None, None]]
>>> initialize_2d_list(2, 2, 0)
[[0, 0], [0, 0]]

2. Function Split Array

Apply a predicate function to each element of a list and split the list into two parts: elements for which the function returns True and those for which it returns False.

def bifurcate_by(lst, fn):
    return [
        [x for x in lst if fn(x)],
        [x for x in lst if not fn(x)]
    ]

Example:

>> bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
[['beep', 'boop', 'bar'], ['foo']]

3. Intersection By

Return the elements from the first list that have matching values in the second list according to a mapping function.

def intersection_by(a, b, fn):
    _b = set(map(fn, b))
    return [item for item in a if fn(item) in _b]

Example:

>> from math import floor
>>> intersection_by([2.1, 1.2], [2.3, 3.4], floor)
[2.1]

4. Max Value Index

Return the index of the maximum element in a list.

def max_element_index(arr):
    return arr.index(max(arr))

Example:

>> max_element_index([5, 8, 9, 7, 10, 3, 0])
4

5. Symmetric Difference

Return the elements that appear in only one of the two lists.

def symmetric_difference(a, b):
    _a, _b = set(a), set(b)
    return [item for item in a if item not in _b] + [item for item in b if item not in _a]

Example:

>> symmetric_difference([1, 2, 3], [1, 2, 4])
[3, 4]

6. Clamp Number

Clamp a number to stay within a given range.

def clamp_number(num, a, b):
    return max(min(num, max(a, b)), min(a, b))

Examples:

>> clamp_number(2, 3, 10)
3
>>> clamp_number(7, 3, 10)
7
>>> clamp_number(124, 3, 10)
10

7. Map Values

Create a new dictionary by applying a function to each value of the original dictionary.

def map_values(obj, fn):
    ret = {}
    for key in obj.keys():
        ret[key] = fn(obj[key])
    return ret

Example:

>> users = {'fred': {'user': 'fred', 'age': 40}, 'pebbles': {'user': 'pebbles', 'age': 1}}
>>> map_values(users, lambda u: u['age'])
{'fred': 40, 'pebbles': 1}
>>> map_values(users, lambda u: u['age'] + 1)
{'fred': 41, 'pebbles': 2}

8. Decapitalize

Lowercase the first character of a string; optionally uppercase the rest.

def decapitalize(s, upper_rest=False):
    return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])

Examples:

>> decapitalize('FooBar')
'fooBar'
>>> decapitalize('FooBar', True)
'fOOBAR'

9. Sum By

Sum the results of applying a function to each element of a list.

def sum_by(lst, fn):
    return sum(map(fn, lst))

Example:

>> sum_by([{'n': 4}, {'n': 2}, {'n': 8}], lambda v: v['n'])
14

10. Count Occurrences

Count how many times a specific value appears in a list (type‑matched).

def count_occurrences(lst, val):
    return len([x for x in lst if x == val and type(x) == type(val)])

Example:

>> count_occurrences([1, 1, 2, 1, 2, 3], 1)
3

11. Chunk (Array Re‑group)

Split a list into sub‑lists of a given size; the last chunk may contain fewer elements.

def chunk(lst, size):
    return [lst[i:i+size] for i in range(0, len(lst), size)]

Example:

>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
Chunk example
Chunk example

12. Digitize (Number to Array)

Convert an integer into a list of its digits.

def digitize(n):
    return list(map(int, str(n)))

Example:

>> digitize(123)
[1, 2, 3]

13. Non‑Recursive Fibonacci

Generate the Fibonacci sequence up to the n‑th index without recursion.

def fibonacci(n):
    a, b = 0, 1
    result = [a]
    for _ in range(n):
        result.append(b)
        a, b = b, a + b
    return result

Example:

>> fibonacci(7)
[0, 1, 1, 2, 3, 5, 8, 13]
Fibonacci example
Fibonacci example

14. Snake Case Conversion

Convert any string to snake_case, handling spaces, hyphens, and camelCase.

def snake(s):
    import re
    s = re.sub(r'[-\s]+', '_', s)
    s = re.sub(r'([A-Z]+)', r' \1', s)
    s = re.sub(r'([A-Z][a-z]+)', r' \1', s)
    return '_'.join(s.lower().split())

Examples:

>> snake('camelCase')
'camel_case'
>>> snake('some text')
'some_text'
>>> snake('some-mixed_string With spaces_underscores-and-hyphens')
'some_mixed_string_with_spaces_underscores_and_hyphens'
>>> snake('AllThe-small Things')
'all_the_small_things'
Snake case conversion example
Snake case conversion example

This collection of short, practical Python functions can boost productivity and deepen understanding of common programming patterns.

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.

algorithmPythonData Structurescode snippetsutilities
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.