Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all iterations of a list of lists?

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]]]
like image 948
Xylot Avatar asked Nov 20 '25 06:11

Xylot


1 Answers

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]]]
like image 100
Ajax1234 Avatar answered Nov 22 '25 18:11

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!