Split list into smaller lists (split in half)
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2
--
Chapters
00:00 Question
00:26 Accepted answer (Score 323)
00:42 Answer 2 (Score 102)
01:05 Answer 3 (Score 52)
01:20 Answer 4 (Score 41)
01:44 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2
--
Chapters
00:00 Question
00:26 Accepted answer (Score 323)
00:42 Answer 2 (Score 102)
01:05 Answer 3 (Score 52)
01:20 Answer 4 (Score 41)
01:44 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.