Let's say I have the list:
a = [[1,2], [3,4,5], [6,7,8,9]]
I'm looking to get all of the iterations of the list like this:
[[1], None, None]
[[1,2], None, None]
[[1,2], [3], None]
[[1,2], [3,4], None]
[[1,2], [3,4,5], None]
[[1,2], [3,4,5], [6]]
[[1,2], [3,4,5], [6,7]]
[[1,2], [3,4,5], [6,7,8]]
[[1,2], [3,4,5], [6,7,8,9]]
With the final output being a list of those iterations:
result = [[[1], None, None], [[1,2], None, None], ... , [[1,2], [3,4,5], [6,7,8,9]]]
You can use a list comprehension:
a = [[1,2], [3,4,5], [6,7,8,9]]
new_a = [a[:i]+[b[:k]]+[None]*(len(a)-i-1) for i, b in enumerate(a) for k in range(len(b)+1) if b[:k]]
Output:
[[[1], None, None],
[[1, 2], None, None],
[[1, 2], [3], None],
[[1, 2], [3, 4], None],
[[1, 2], [3, 4, 5], None],
[[1, 2], [3, 4, 5], [6]],
[[1, 2], [3, 4, 5], [6, 7]],
[[1, 2], [3, 4, 5], [6, 7, 8]],
[[1, 2], [3, 4, 5], [6, 7, 8, 9]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With