Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list into smaller lists (split in half)

Tags:

python

list

split

People also ask

How do I separate lists within a list?

Use a semicolon to separate items in a list in cases where one or more of the items contains commas or other punctuation. Usually, we use a comma to separate three items or more in a list.

How do you split a list into evenly sized chunks?

The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.

How do you split a big list into smaller lists in Python?

Method #1: Using islice to split a list into sublists of given length, is the most elegant way. # into sublists of given length. Method #2: Using zip is another way to split a list into sublists of given length.


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)

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)

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


def split(arr, size):
     arrs = []
     while len(arr) > size:
         pice = arr[:size]
         arrs.append(pice)
         arr   = arr[size:]
     arrs.append(arr)
     return arrs

Test:

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(split(x, 5))

result:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]

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.


B,C=A[:len(A)/2],A[len(A)/2:]