The Python Oracle

Split list into smaller lists (split in half)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation

--

Chapters
00:00 Split List Into Smaller Lists (Split In Half)
00:18 Accepted Answer Score 345
00:31 Answer 2 Score 106
00:50 Answer 3 Score 53
01:00 Answer 4 Score 23
01:19 Thank you

--

Full question
https://stackoverflow.com/questions/7523...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #split

#avk47



ACCEPTED ANSWER

Score 345


A = [1,2,3,4,5,6]
B = A[:len(A)//2]
C = A[len(A)//2:]

If you want a function:

def split_list(a_list):
    half = len(a_list)//2
    return a_list[:half], a_list[half:]

A = [1,2,3,4,5,6]
B, C = split_list(A)



ANSWER 2

Score 106


A little more generic solution (you can specify the number of parts you want, not just split 'in half'):

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
             for i in range(wanted_parts) ]

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

print split_list(A, wanted_parts=1)
print split_list(A, wanted_parts=2)
print split_list(A, wanted_parts=8)



ANSWER 3

Score 53


f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)

n - the predefined length of result arrays




ANSWER 4

Score 23


If you don't care about the order...

def split(list):  
    return list[::2], list[1::2]

list[::2] gets every second element in the list starting from the 0th element.
list[1::2] gets every second element in the list starting from the 1st element.