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]]
4. Rotate a List
Rotate the elements of a list by n positions.
def rotate(lst, n):
return lst[-n:] + lst[:-n]
lst = [1, 2, 3, 4, 5]
rotated_lst = rotate(lst, 2)
print(rotated_lst)
[4, 5, 1, 2, 3]
5. Find Duplicates in a List
Identify duplicate elements in a list.
from collections import Counter
lst = [1, 2, 2, 3, 4, 4, 4, 5]
duplicates = [item for item, count in Counter(lst).items() if count > 1]
print(duplicates)
[2, 4]
6. Chunk a List
Split a list into evenly sized chunks.
def chunk(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
lst = [1, 2, 3, 4, 5, 6, 7, 8]
chunks = list(chunk(lst, 3))
print(chunks)
[[1, 2, 3], [4, 5, 6], [7, 8]]
7. Remove Consecutive Duplicates
Remove consecutive duplicates from a list, preserving order.
from itertools import groupby
lst = [1, 2, 2, 3, 3, 3, 4, 4, 5]
result = [key for key, _ in groupby(lst)]
print(result)
[1, 2, 3, 4, 5]
0 Comments:
Post a Comment