Create two lists from list of tuples

Viewed 79

I want to create two lists based on sorted_bounds with every other tuple.

bounds = [1078.08, 1078.816, 1078.924, 1079.348, 1079.448, 1079.476]
sorted_bounds = list(zip(bounds,bounds[1:]))
print(sorted_bounds)
# -> [(1078.08, 1078.816), (1078.816, 1078.924), (1078.924, 1079.348), (1079.348, 1079.448), (1079.448, 1079.476)]

Desired output:

list1 = [(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]  
list2 = [(1078.816, 1078.924), (1079.348, 1079.448)]

How would I do this? I am completely blanking.

2 Answers
list1 = sorted_bounds[0::2]
list2 = sorted_bounds[1::2]

The third value in brackets is "step", so every second element in this case.

Trying to think of a way of doing this in a single pass, but here's a clean way to do it in two passes:

list1 = [x for i, x in enumerate(sorted_bounds) if not i % 2]
list2 = [x for i, x in enumerate(sorted_bounds) if i % 2]
print(list1)
print(list2)

Result:

[(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]
[(1078.816, 1078.924), (1079.348, 1079.448)]
Related