Skip to content

Instantly share code, notes, and snippets.

@t-eckert
Last active June 1, 2021 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-eckert/a31f61bbc2e1da5ad63eb1293bd776f4 to your computer and use it in GitHub Desktop.
Save t-eckert/a31f61bbc2e1da5ad63eb1293bd776f4 to your computer and use it in GitHub Desktop.
Haskell's `inits` in Python
from typing import Iterable
def inits(items: Iterable) -> list[Iterable]:
"""Given an iterable, returns all of its prefixes in ascending order of length
Arguments:
items: Iterable items whose prefixes will be returned
Returns:
list[Iterable] prefixes of the iterable
Example:
``` python
inits([4, 3, 2, 1]) # returns [[], [4], [4,3], [4,3,2], [4,3,2,1]]
```
"""
return [items[:n] for n in range(len(items) + 1)]
numbers = [4, 3, 2, 1]
print(inits(numbers))
letters = "abcdefg"
print(inits(letters))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment