I have a python list as follows:
list_ = [-100, 1, 3, 5, 7, 100]
I want to create another list such as below; (Note that the last 100 is not included!!)
new_list = [[-100], [-100, 1], [-100, 1, 3], [-100, 1, 3, 5], [-100, 1, 3, 5, 7]]
I tried as follows:
new_list = []
for i in list_:
new_list.append(list([i]))
It generates [[-100], [1], [3], [5], [7], [100]], which is not the one I want.
Is this want you want?
l = [-100, 1, 3, 5, 7, 100]
print([l[:i+1] for i in range(0, len(l) - 1)])
Output:
[[-100], [-100, 1], [-100, 1, 3], [-100, 1, 3, 5], [-100, 1, 3, 5, 7]]
Or even simpler:
print([l[:i] for i in range(1, len(l))])
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