'How do you create a telescoping set of terms in python?

I'm trying to animate a line moving through a maze and was wondering if there was a way to easily make a telescoping list.

For instance, bfs(grid) returns a list of coordinate pairs, e.g.

[(0,1),(0,2),(0,3)....]

and I was wondering if there was a way to take that list and return

[[(0,1)] , [(0,1), (0,2)] , [(0,1) , (0,2), (0,3)]]


Solution 1:[1]

With recent (> 3.8) versions of Python you make good use of the walrus operator for this:

l = [(0,1),(0,2),(0,3)]
x = []

[x := x + [t] for t in l]
# [[(0, 1)], [(0, 1), (0, 2)], [(0, 1), (0, 2), (0, 3)]]

Solution 2:[2]

You can use list slicing with a list comprehension:

[lst[:idx + 1] for idx in range(len(lst))]

This outputs:

[[(0, 1)], [(0, 1), (0, 2)], [(0, 1), (0, 2), (0, 3)]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark
Solution 2 BrokenBenchmark