How To Split A List In Python

Share This Post

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:]




[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?


Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img