Paul Paul - 2 months ago 22
Python Question

Separate list into two equal parts with slices

I need to write a function that splits any list into two equal parts. If length of list is even, I want just split it it two parts, and if length of the list is odd, I want to ignore central element.

So [1,2,3,4,5,6] => [1,2,3] and [4,5,6]
and [1,2,3,4,5] => [1,2] and [4,5]


I tried to do the following way:

list = [1,100,50,-51,1,1]
s = len(list)/2
left = list[s+1:]
right = list[:s]


But this approach doesnt work both for even and odd lengths.
Is there a way to use slices for this purpose or there is no way and it's better to use loops/iterations?

Answer

Use divmod on the length of the list and 2. Right slice is taken from sum of the quotient and the remainder:

lst = [1,100,50,-51,1,1]

s = divmod(len(lst), 2)
left = lst[:s[0]]
right = lst[sum(s):]