Skip to content

How To Split A List In Python

  • by
Split A List In Python

The size of the chunk defined can be used to split a list. When you split a list into n parts, you get a list of n lists, each with the same amount of list components. Some lists will have one more element than others if the number of lists, n, does not evenly divide into the length of the list being divided. Let’s do it the old-fashioned way and divide the list.

Python list segmentation

To split a list, use the len (iterable) method with iterable as a list to discover its length, then use the / operator to floor divide the length by 2 to find the list’s middle index.


list = [11, 18, 19, 21]

length = len(list)

middle_index = length // 2

first_half = list[:middle_index]

second_half = list[middle_index:]

print(first_half)

print(second_half)

Output

[11, 18]

[19, 21]

Split A List In Python

As you can see from the output, the list was split exactly in half. To get to the first and second halves of the split list, we utilized the colon operator(:).

How to split a list into n parts in Python

In Python, how do you break a list into n parts Use the numpy.array split() method in Python to split a list into n sections. The function np.split() divides an array into numerous sub-arrays.

The numpy array split() method returns a list of n Numpy arrays, each with about the same amount of elements as the original list.

Read more: How To Sort A List Of Tuples In Python?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *