Member-only story
7 Lesser-Known Python Techniques about Lists
2 min readAug 27, 2024
1. Flatten a Nested List
Flatten a deeply nested list into a single list of elements.
from collections.abc import Iterable
def flatten(lst):
for item in lst:
if isinstance(item, Iterable) and not isinstance(item, str):
yield from flatten(item)
else:
yield item
nested_list = [1, [2, 3, [4, 5]], 6]
flat_list = list(flatten(nested_list))
print(flat_list)
[1, 2, 3, 4, 5, 6]
2. List of Indices for Specific Value
Get all indices of a specific value in a list.
lst = [10, 20, 10, 30, 10, 40]
indices = [i for i, x in enumerate(lst) if x == 10]
print(indices)
[0, 2, 4]
3. Transpose a List of Lists (Matrix)
Transpose a matrix-like list (switch rows and columns).
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(map(list, zip(*matrix)))
print(transposed)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]