Reputation: 5
How can I turn a list such as:
og_list = [0, 4, 12, 18, 20, 23]
into a nested list such as:
new_list = [[0, 4], [4, 12], [12, 18], [18, 20], [20, 23]]
How can I achieve this?
Upvotes: 0
Views: 46
Reputation: 17156
og_list = [0, 4, 12, 18, 20, 23]
new_list = [list(x) for x in zip(og_list, og_list[1:])]
print(new_list) # [0, 4], [4, 12], [12, 18], [18, 20], [20, 23]]
Upvotes: 0
Reputation: 717
og_list = [0, 4, 12, 18, 20, 23]
new_list = [[og_list[i],og_list[i+1]] for i in range(len(og_list)-1)]
print(new_list)
Alternatively you can also use itertools module as below:
from itertools import cycle
og_list = [0, 4, 12, 18, 20, 23]
licycle = cycle(og_list)
next(licycle)
new_list = [[i,next(licycle)] for i in og_list]
print(new_list)
Upvotes: 0
Reputation: 2443
new_list = []
for i in range(len(og_list)-1):
new_list.append( [og_list[i],og_list[i+1]] )
Upvotes: 1