Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a sublist from a python list

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.

like image 896
Mass17 Avatar asked Jun 28 '26 12:06

Mass17


1 Answers

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))])
like image 74
baduker Avatar answered Jun 30 '26 09:06

baduker



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!