'How to split interval in two

How can i split this interval using python?

I have this interval:

x = [10, 30]

I want to split it in 2 using python code to get this:

y = [10, 20] 
z = [20, 30]


Solution 1:[1]

A general purpose sol:

def interval(l, n):
    w = (l[1] - l[0]) // n
    return [[l[0]+i*w, l[0]+(i+1)*w] for i in range(n)]

so, in your case:

interval([10, 30], 2)
#[[10, 20], [20, 30]]

but you can also ask for more intervals:

interval([10, 30], 4)
#[[10, 15], [15, 20], [20, 25], [25, 30]]

Solution 2:[2]

yeah, just compute the middle of the interval once, and reuse it for the second tuple:

x = [10, 30]
y = [x[0],(x[1]+x[0])//2]
z = [y[1],x[1]]

print(y,z)

result:

[10, 20] [20, 30]

Solution 3:[3]

Solution:

x = [10, 30]

y = [x[0], x[0] + (x[1] - x[0]) // 2]
z = [y[1], x[1]]

print(y, z)

Output: [10, 20] [20, 30]

Solution 4:[4]

A bit late, but i hope this solution will help others. I think this solution is a bit faster, because it doesn't loop that much.

def split_list(list, split_length):
"""splits a list in a interval"""
split_count = (len(list) // split_length) + 1
splitted_list_list = []
for i in range(1, split_count + 1):
    new_segment = list[(i-1) * split_length: i * split_length]
    if len(new_segment) >0:
        splitted_list_list.append(new_segment)
return splitted_list_list

Example:

print(split_list([1, 2, 3, 4, 5, 6, 7, 8, 9], 2))

Output:

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe Iddon
Solution 2 Jean-François Fabre
Solution 3 Flaming_Dorito
Solution 4 ImEcho