flatten - Flatten Nested Lists
Flatten a List of Lists into a single List.
Example
from capturegraph.data import flatten
# sessions.photos is List[List[Path]]
# (each session has multiple photos)
all_photos = flatten(sessions.photos)
# → List[Path] with all photos from all sessions
flatten(nested)
Flatten a List of Lists into a single List.
Parameters:
| Name |
Type |
Description |
Default |
nested
|
List[List[T]]
|
A List where each element is itself a List.
|
required
|
Returns:
| Type |
Description |
List[T]
|
A single flattened List containing all elements.
|
Example
photos_per_session = List([
List([Path("a.jpg"), Path("b.jpg")]),
List([Path("c.jpg")])
])
flatten(photos_per_session)
# List([Path("a.jpg"), Path("b.jpg"), Path("c.jpg")])
Source code in capturegraph-lib/capturegraph/data/containers/utilities/flatten.py
| def flatten[T](nested: List[List[T]]) -> List[T]:
"""Flatten a List of Lists into a single List.
Args:
nested: A List where each element is itself a List.
Returns:
A single flattened List containing all elements.
Example:
```python
photos_per_session = List([
List([Path("a.jpg"), Path("b.jpg")]),
List([Path("c.jpg")])
])
flatten(photos_per_session)
# List([Path("a.jpg"), Path("b.jpg"), Path("c.jpg")])
```
"""
result: list[T] = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
elif isinstance(item, dict):
result.extend(flatten(item.values()))
else:
result.append(item)
return List(result)
|