Python Code Snippets: Function Chaining, Default Argument Pitfalls, CSV I/O, List Operations, and More
This article presents a collection of Python programming examples covering function chaining, default‑argument traps, CSV file reading and writing, number‑base conversion, list flattening and merging, dictionary utilities, and common algorithmic patterns such as permutations and combinations.
Function Continuous Call
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) # 27JavaScript 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)//27Default‑Value Trap
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
import 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) # 10List Flattening
list_ = [[1,2,3],[4,5,6],[7,8,9]]
[k for i in list_ for k in i]
import numpy as np
print np.r_[[1,2,3],[4,5,6],[7,8,9]]
import itertools
print list(itertools.chain(*[[1,2,3],[4,5,6],[7,8,9]]))
sum(list_, [])
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
flatten(list_)List Merging
a = [1,3,5,7,9]
b = [2,3,4,5,6]
c = [5,6,7,8,9]
list(set().union(a, b, c))Most Common Two Letters
from collections import Counter
c = Counter('hello world')
print(c.most_common(2)) # [('l', 3), ('o', 2)]Cautious Use of eval eval("__import__('os').system('rm -rf /')", {}) Permutation Matrix
matrix = [[1,2,3],[4,5,6]]
res = zip(*matrix) # [(1,4), (2,5), (3,6)]List Comprehension Examples
[item**2 for item in lst if item % 2]
map(lambda item: item ** 2, filter(lambda item: item % 2, lst))
list(map(str, [1,2,3,4,5,6,7,8,9]))Permutations and Combinations
import itertools
for p in itertools.permutations([1,2,3,4]):
print(''.join(str(x) for x in p))
for c in itertools.combinations([1,2,3,4,5], 3):
print(''.join(str(x) for x in c))
for c in itertools.combinations_with_replacement([1,2,3], 2):
print(''.join(str(x) for x in c))
for p in itertools.product([1,2,3], [4,5]):
print(p)Default Dictionary 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]'Reverse Dictionary
m = {'a':1, 'b':2, 'c':3, 'd':4}
rev = {v:k for k,v in m.items()}
print(rev) # {1:'a', 2:'b', 3:'c', 4:'d'}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
