Rewrite Multi‑Line Functions Using Python Lambda – Surprising Tricks
Explore unconventional Python techniques—including simulating multi‑line functions with lambda expressions, clever ternary operator shortcuts, list‑comprehension methods for deduplication, generating Fibonacci sequences, and mutable default arguments—while highlighting pitfalls and performance considerations for each trick.
Rewrite Multi‑Line Functions Using Lambda
Python's lambda expressions normally support only single expressions, but they can be crafted to mimic multi‑line functions.
def f(): x = 'string' if x.endswith('g'): x = x[:-1] r = '' for i in xrange(len(x)): if x[i] != 'i': r += x[i] return r # Equivalent lambda expression (lambda: ([x for x in x if not x.endswith('g')], r)[-1])()
Ternary Operator Shortcut
Python's ternary syntax b if a else c can be expressed using logical operators.
(a and [b] or [c])[0]
Remove Duplicates with List Comprehensions
Several approaches to deduplicate a string using list comprehensions, reduce, and loops.
# Simple comprehension ''.join(['' if i and j == x[i-1] else j for i, j in enumerate(x)]) # Using reduce from functools import reduce reduce(lambda a, b: a + b if a.endswith(b) else a + b, x, '')
Generate Fibonacci Sequence via List Comprehensions
Fibonacci numbers can be generated by storing intermediate values in a list.
[l.append(l[-1] + l[-2]) or l for l in [[1, 1]] for x in xrange(10)][0]
List Slicing Tricks
Common list operations: copying, removing/replacing elements, adding to the front or back, and reversing.
# Copy list m = l[:] # Replace element l = [4, 5, 6, 7] # Add to front l = [4, 5, 6] + l[:0] # Add to back l = l + [4] # Reverse list l = l[::-1]
Replace Method Bytecode
Python prevents direct replacement of instance methods, but the underlying bytecode can be swapped.
class A(object): def x(self): print "hello" def y(self): print "world" a = A() a.x.im_func = a.y # Raises TypeError # Bytecode replacement a.x.im_func.func_code = a.y.func_code print a.x() # Outputs "world"
Mutable Default Arguments
Using mutable objects as default arguments is risky, yet useful for caching.
def f(n, c={}): if n in c: return c[n] if n < 2: r = 1 else: r = n * f(n-1, c) c[n] = r return r print f(10) # 3628800 print f.func_defaults # ({1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880, 10: 3628800},) def fib(n, c={}): if n in c: return c[n] if n < 2: r = 1 else: r = fib(n-2, c) + fib(n-1, c) c[n] = r return r print fib(10) # 89 print fib.func_defaults[0].values() # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
These snippets demonstrate powerful, albeit sometimes unsafe, Python tricks that can simplify code or improve performance when used judiciously.
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.
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.
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.
