Fundamentals 6 min read

Master Python Tricks: Function Chaining, Default Argument Pitfalls, CSV I/O, and More

This article showcases a collection of practical Python snippets covering function chaining, mutable default argument traps, CSV reading and writing, number base conversion, JSON formatting, list flattening and merging, most‑common character counting, safe eval usage, matrix transposition, list comprehensions, permutations/combinations, defaultdict usage, and dictionary reversal techniques.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Tricks: Function Chaining, Default Argument Pitfalls, CSV I/O, and More

Function Chaining

def add(x):
    class AddNum(int):
        def __call__(self, x):
            return AddNum(self.numerator + x)
    return AddNum(x)

print(add(2)(3)(5))  # 10
print(add(2)(3)(4)(5)(6)(7))  # 27

# JavaScript version
var add = function(x){
    var addNum = function(x){
        return add(addNum + x);
    };
    addNum.toString = function(){
        return x;
    }
    return addNum;
}
add(2)(3)(5) // 10
add(2)(3)(4)(5)(6)(7) // 27

Default Argument Pitfall

def evil(v=[]):
    v.append(1)
    print(v)

evil()  # [1]
evil()  # [1, 1]

Read/Write CSV Files

import csv

with open('data.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# Write to CSV
with open('data.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(['name', 'address', 'age'])
    data = [
        ('xiaoming', 'china', '10'),
        ('Lily', 'USA', '12')
    ]
    writer.writerows(data)

Number Base Conversion

int('1000', 2)  # 8
int('A', 16)    # 10

JSON Formatting

echo '{"k": "v"}' | python -m json.tool

List Flattening

list_ = [[1,2,3],[4,5,6],[7,8,9]]
flattened = [k for i in list_ for k in i]
# Using numpy
import numpy as np
print(np.r_[[1,2,3],[4,5,6],[7,8,9]])
# Using itertools
import itertools
print(list(itertools.chain(*list_)))
flatten = lambda x: [y for l in x for y in flatten(l)] if isinstance(x, list) else [x]
print(flatten(list_))

List Merging

a = [1,3,5,7,9]
b = [2,3,4,5,6]
c = [5,6,7,8,9]
merged = list(set().union(a, b, c))
print(merged)  # [1,2,3,4,5,6,7,8,9]

Most Common Two Letters

from collections import Counter
c = Counter('hello world')
print(c.most_common(2))  # [('l', 3), ('o', 2)]

Eval Caution

eval("__import__('os').system('rm -rf /')", {})

Matrix Transposition

matrix = [[1,2,3],[4,5,6]]
res = list(zip(*matrix))  # [(1,4), (2,5), (3,6)]

List Comprehension

[item**2 for item in lst if item % 2]
# Equivalent using map and filter
map(lambda item: item**2, filter(lambda item: item % 2, lst))
print(list(map(str, range(1,10))))

Permutations and Combinations

import itertools
# Permutations of [1,2,3,4]
for p in itertools.permutations([1,2,3,4]):
    print(''.join(str(x) for x in p))
# Combinations of 5 elements taken 3 at a time
for c in itertools.combinations([1,2,3,4,5], 3):
    print(''.join(str(x) for x in c))
# Combinations with replacement of [1,2,3] taken 2 at a time
for c in itertools.combinations_with_replacement([1,2,3], 2):
    print(''.join(str(x) for x in c))
# Cartesian product of [1,2,3] and [4,5]
for p in itertools.product([1,2,3], [4,5]):
    print(p)

Defaultdict Usage

import collections
m = collections.defaultdict(int)
print(m['a'])  # 0
m = collections.defaultdict(str)
print(m['a'])  # ''
m = collections.defaultdict(lambda: '[default value]')
print(m['a'])  # [default value]

Dictionary Reversal

m = {'a':1, 'b':2, 'c':3, 'd':4}
reversed_dict = {v: k for k, v in m.items()}
print(reversed_dict)  # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
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 StructuresAlgorithmscode snippets
MaGe Linux Operations
Written by

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.

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.