Question and Answer

how to split a list in python

Splitting a list in half results in two smaller lists containing elements from the original in the same order. For example, splitting [1, 2, 3, 4] in half results in [1, 2] and [3, 4].

SPLIT THE LIST IN HALF

Call len(iterable) with iterable as a list to find its length.

Floor divide the length by 2 using the // operator to find the middle_index of the list.

Use the slicing syntax list[:middle_index] to get the first half of the list and list[middle_index:] to get the second half of the list.

print(a_list)
OUTPUT
[1, 2, 3, 4]
length = len(a_list)
middle_index = length//2

Floor division rounds down


first_half = a_list[:middle_index]

Slice first half


print(first_half)
OUTPUT
[1, 2]
second_half = a_list[middle_index:]

Slice second half


print(second_half)
OUTPUT
[3, 4]
Related Articles