âGiven each iterable we construct a tuple by adding an index.
a = ['Hello','world','!']list(enumerate(a))â# [(0, 'Hello'), (1, 'world'), (2, '!')]
âConcatenating iterable to a single string.
a = ["python","really","rocks"]" ".join(a)# 'python really rocks'
â
Combining two iterable of tuples or pivot nested iterables.
# Combining two iterablesa = [1,2,3]b = ['a','b','c']z =zip(a, b)z# [(1, 'a'), (2, 'b'), (3, 'c')]# Pivoting list of tupleszip(*z)# [(1, 2, 3), ('a', 'b', 'c')]
â
Getting min/max from iterable (with/without specific function).
# Getting maximum from iterable>>> a = [1,2,-3]>>>max(a)# 2# Getting maximum from iterable>>>min(a)# 1# Bot min/max has key value to allow to get maximum by appliing function>>>max(a,key=abs)# 3
âGetting sorted iterable (can sort by âcompareâ function).
>>> a = [1,2,-3]>>>sorted(a)# [-3, 1, 2]>>>sorted(a,key=abs)# [1, 2, -3]
âSplitting a single string to list.
>>> s ="a,b,c">>> s.split(",")# ["a", "b", "c"]
â
Initializing a list filled with some repetitive number.
[1]*10# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
â
Merging/Upserting two dictionaries.
>>> a ={"a":1,"b":1}>>> b ={"b":2,"c":1}>>> a.update(b)>>> a# {"a":1, "b":2, "c":1}
Finding the index of the min/max item in an iterable.
a = [2,3,1]min(enumerate(a),key=lambdax: x[1])[0]# 2
â
Rotating iterable by k elements.
>>> a = [1,2,3,4]>>> k =2>>> a[-2:]+ a[:-2]â# [3, 4, 1, 2]â
Removing useless characters on the end/start/both of your string.
>>> name ="//George//">>> name.strip("/")#'George'>>> name.rstrip("/")#'//George'>>> name.lstrip("/")#'George//'
â
Reversing an iterable wit order (string, list etc).
# Reversing string>>> s ="abc">>> s[::-1]# "cba"# Reversing list>>> l = ["a","b","c"]>>> l[::-1]#["c", "b", "a"]
â2. Python branching tricks
Multiple predicates short-cut.
n =101< n <20# True
For-else construct useful when searched for something and find it.
# For example assume that I need to search through a list and process each item until a flag item is found and # then stop processing. If the flag item is missing then an exception needs to be raised.for i in mylist:if i == theflag:breakprocess(i)else:raiseValueError("List argument missing terminal flag.")
Trenary operator.
"Python ROCK"ifTrueelse" I AM GRUMPY"# "Python ROCK"
i =5while i >1:print("Whil-ing away!") i -=1if i ==3:breakelse:print("Finished up!")
3. Python comprehensions tricks
List comprehension.
>>> m = [x **2for x inrange(5)]>>> m# [0, 1, 4, 9, 16]
Set comprehension.
>>> m ={x **2for x inrange(5)}>>> m# {0, 1, 4, 9, 16}
Dict comprehension.
m ={x: x **2for x inrange(5)}m# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Generator comprehension.
# A generator comprehension is the lazy version of a list comprehension.>>> m = (x **2for x inrange(5))>>> m# <generator object <genexpr> at 0x108efe408>>>>list(m)# [0, 1, 4, 9, 16]>>> m = (x **2for x inrange(5))>>>next(m)# 0>>>list(m)# [1, 4, 9, 16]
List comprehension with the current and previous value.
>>> a = [1,2,4,2]>>> [y - x for x,y inzip(a,a[1:])]# [1, 2, -2]
Note: all comprehension can use predicates with if statement.
4. Python unpacking tricks
Unpack variables from iterable.
# One can unpack all iterables (tuples, list etc)>>> a, b, c =1,2,3>>> a, b, c# (1, 2, 3)>>> a, b, c = [1,2,3]>>> a, b, c# (1, 2, 3)
Swap variables values.
>>> a, b =1,2>>> a, b = b, a>>> a, b# (2, 1)
Unpack variables from iterable without indicating all elements.
# This creates a randomized 128-bit number that will almost certainly be unique.
# In fact, there are over 2ÂđÂēÂē possible UUIDs that can be generated. Thatâs over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).
>>> import uuid
>>> user_id = uuid.uuid4()
>>> user_id
# UUID('7c2faedd-805a-478e-bd6a-7b26210425c7')
Memoization using LRU cache.
import functools
@functools.lru_cache(maxsize=128)
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
Suppression of expressions
>>> from contextlib import suppress
>>> with contextlib.suppress(ZeroDivisionError):
>>> 10/0
# No exception raised
An elegant way to deal with a file path (3.4âĨ)
>>> from pathlib import Path
>>> data_folder = Path("source_data/text_files/")
# Path calculation and metadata
>>> file_to_open = data_folder / "raw_data.txt"
>>> file_to_open.name
# "raw_data.txt"
>>> file_to_open.suffix
# "txt"
>>>file_to_open.stem
# "raw_data"
# Files functions
>>> f = open(file_to_open)
>>> f.read()
# content of the file
>>> file_to_open.exists()
# True
>>> def foo(lst):
>>> for x in lst:
>>> yield x
>>> yield x*2
>>> a = [1, 3]
>>> list(foo(a))
# [1, 2, 3, 6]
8. Python easter eggs
Anti-gravity
import antigravity
antigravity.fly()
The Zen of Python
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one and preferably only one obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea let's do more of those!