Splitting list in python

How to Split the Elements of a List in Python?

In Python, lists are used to store multiple items/elements of any data type in a single variable. To split the list’s elements/items, various inbuilt functions, including some standard modules, are used in Python. For instance, the split() method, list comprehension, partition() function, etc., are used to split the list elements in Python.

This write-up will provide a detailed guide on splitting the elements of a list in Python using numerous examples. The following methods are discussed in this Python guide:

  • Method 1: Using split() Method
  • Method 2: Using List Comprehension
  • Method 3: Using numpy.array_split() Function
  • Method 4: Using partition() Method

Method 1: Using split() Method

In the example given below, the “split()” method is used to split the elements of the list and retrieve the specific part of the list elements.

Code-1: (Split the list elements and return list of string)

list_value = ['1-Alex', '2-John', '3-David', '4-Lily'] output = [i.split('-')[1] for i in list_value] print(output)
  • The list contains combined numeric and character string values.
  • The “split()” method is used along with list comprehension to split the numeric and string parts of the list elements and return the list of string values.
  • From the above snippet, it can be seen that alphabetic strings are placed at index 1, and numeric strings are placed at index 0.
  • Since we want to get only alphabetic strings from the given list. Therefore, we utilized the index “[1]” with the split() function.

The list of strings is created successfully in the above output.

In the code given below, the “split()” method is again used to split the list element and return the numeric strings instead of alphabetic strings.

Code-2: (Split the element of the list and return a list of numeric strings)

list_value = ['1-Alex', '2-John', '3-David', '4-Lily'] output = [i.split('-')[0] for i in list_value] print(output)
  • We used index position “0” instead of “1” with the split() method to get the list of numeric strings. The snippet below will clarify where we made changes in the code:
Читайте также:  Css position relative to document

The above output shows the list of numeric strings.

In the code given below, the “split()” method is used to split the items of the list into nested lists. Skipping the index position from the split()function will return all the list elements as a nested list:

Code-3: (Split the element of the list and return nested list )

list_value = ['1-Alex', '2-John', '3-David', '4-Lily'] output = [i.split('-') for i in list_value] print(output)
  • The “split()” method is used along with list comprehension and for loop to split the elements of a list into the nested list. The “-” symbol is passed to the split() function as a separator.

The above output shows that the split() function splits the input list into nested lists.

Method 2: Using List Comprehension

In the example code given below, list comprehension is used along with string slicing to split the elements of the list according to the specified size.

list_value = ['John', 'Alex', 43, 90, 55, 34] step_size = 3 # using list comprehension new_list = [list_value[i:i + step_size] for i in range(0, len(list_value), step_size)] print("\nGiven List: \n") print(list_value) print("\nAfter Splitting List: \n") print(new_list)
  • An alpha-numeric list is created in the program.
  • The step size or each chunk size is stored in a variable named “step_size”.
  • The “List Comprehension” is used along with the combination of the “for” loop to iterate over the list and split the elements of the list according to specified step size.
  • The slicing of the list concept is also combined in the list comprehension to split the list element.

In the above output, the element of the list is split according to the specified step size.

Method 3: Using numpy.array_split() Function

In the example code given below, the “numpy.array_split()” function of the “numpy” package is used to split the given list into sublists based on the specified size.

import numpy list_value = ['1','Alex', '2','John', '3','David', '4','Lily','5'] split_items = numpy.array_split(list_value, 3) for array in split_items: print(list(array))
  • The “numpy” library is imported at the start to access the “numpy.array_split()” function.
  • List values containing alpha-numeric strings are initialized and stored in a variable named “list_value”.
  • The “numpy.array_split()” function takes the input list as the first argument and chunk size as the second argument.
  • We passed “3” as a chunk size; therefore, the split() function splits the given list into three separate lists.
  • We utilized the for loop to iterate over the obtained list. Within the “for” loop, we utilized the print() function to print the separated lists.

The above output shows that the array_split() function successfully splits the input list into different lists.

Method 4: Using partition() Method

In the example given below, the “partition()” method of the “toolz” module is used to split the elements of the list according to the specified size.

from toolz import partition list_value = ['1','Alex', '2','John', '3','David', '4','Lily','5'] split_items = list(partition(3, list_value)) print(split_items)
  • The “partition” method is imported from the “toolz” module.
  • The “partition()” method, along with the “list()” function, takes the chunks size of the list and list variable as an argument and returns the list of elements according to the specified size.
Читайте также:  Index php убрать чпу

The above output snippet shows that the list of separated elements was successfully created.

Conclusion

To split the elements of the list, the “split()” methods, “List Comprehension”, “numpy.array_split()”, and “partition()” methods are used in Python. The “split()” method splits the string list according to the specified separator and returns the list of strings. The list comprehension is also used along with the combination of string slicing to split the elements of the list. The “numpy.array_split()” and “partition()” methods are used to split the elements of the list easily and straightforwardly. This article provided a detailed guide on splitting the list’s elements in Python with multiple examples.

Источник

How to Split a List in Python

To split a list in Python, you can use the “len()” method with iterable as a list to find its length, and then floor divide the length by 2 using the “//” operator to find the middle_index of the list.

Example 1: How to Use len() Method to split a list

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)

As you can see from the output, we split the list in exact half. We used the colon operator(:) to access the first and second half of the split list.

Example 2: How to split a list into n parts in Python

To split a list into n parts in Python, use the numpy.array_split() function.

The np.split() function splits the array into multiple sub-arrays.

The numpy array_split() method returns the list of n Numpy arrays, each containing approximately the same number of elements from the list.

import numpy as np listA = [11, 18, 19, 21, 29, 46] splits = np.array_split(listA, 3) for array in splits: print(list(array))

In this example, we split the list into 3 parts.

Example 3: Splitting a List Into Even Chunks of N Elements

A list can be split based on the size of the chunk defined. This means that we can determine the size of the chunk.

If the subset of a list doesn’t fit the size of the defined chunk, fillers need to be inserted in the place of the empty element holders.

Therefore, we will use None as a filter to fill those empty element holders.

def list_split(listA, n): for x in range(0, len(listA), n): every_chunk = listA[x: n+x] if len(every_chunk) < n: every_chunk = every_chunk + \ [None for y in range(n-len(every_chunk))] yield every_chunk print(list(list_split([11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 112, 113], 7)))
[[11, 21, 31, 41, 51, 61, 71], [81, 91, 101, 111, 112, 113, None]]

Method 2: Using list comprehension + zip() + slicing + enumerate()

test_list = [11, 19, 21, 18, 46] print("The original list : " + str(test_list)) size = len(test_list) idx_list = [idx + 1 for idx, val in enumerate(test_list) if val == 21] res = [test_list[i: j] for i, j in zip([0] + idx_list, idx_list + ([size] if idx_list[-1] != size else []))] print("The list after splitting by a value : " + str(res)) 
The original list : [11, 19, 21, 18, 46] The list after splitting by a value : [[11, 19, 21], [18, 46]] 

Method 3: Using for loop+replace()+split()+join()+list()+map()

main_list = [11, 19, 21, 18, 46] print("The original list : " + str(main_list)) x = list(map(str, main_list)) x = " ".join(x) x = x.replace("21", "5*") y = x.split("*") res = [] for i in y: i = i.strip() i = i.split(" ") b = [] for j in i: b.append(int(j)) res.append(b) print("The list after splitting by a value : " + str(res))
The original list : [11, 19, 21, 18, 46] The list after splitting by a value : [[11, 19, 5], [18, 46]]

Method 4: Using list comprehension

Using list comprehension, we can split an “original list” and “create chunks”. To split the list into chunks, provide the N to the “list comprehension” syntax, and it will create a new list with N chunks of elements.

Читайте также:  Settings json vs code python

Example

main_list = [11, 21, 46, 19] split_size = 3 splitted_list = [main_list[i:i+split_size] for i in range(0, len(main_list), split_size)] print(splitted_list)

You can see that we split a list into chunks of 3 elements. You can divide the list into chunks of 2 elements or four elements. Pass the split_size, which is N in our case.

Method 6: Using “itertools”

import itertools def split_list(lst, val): return [list(group) for k, group in itertools.groupby(lst, lambda x: x == val) if not k] main_list = [11, 19, 21, 18, 46] split_lst = split_list(main_list, 21) print("The list after splitting by a value:", split_lst) 
The list after splitting by a value: [[11, 19], [18, 46]]

Method 7: Using for loop

Use a for loop to split the list into different chunks. Define the chunk size of the list, and it will create a list of chunks of that exact size.

Example

main_list = [11, 21, 46, 19] chunk_size = 2 splitted_list = list() for i in range(0, len(main_list), chunk_size): splitted_list.append(main_list[i:i+chunk_size]) print(splitted_list)

Method 8: Using numpy array_split()

The np.array_split() is a numpy library function that splits the list into chunks. It allows you to split an array into a set number of arrays.

Example

import numpy as np main_list = [11, 21, 46, 19] main_array = np.array(main_list) chunked_array = np.array_split(main_list, 2) splitted_list = [list(array) for array in chunked_array] print(splitted_list)

3 thoughts on “How to Split a List in Python”

I really like the second way with the function. Thanks for the clarification, it seems so obvious now! Reply

Merci pour cette page bien que des informations ne sois plus à jour, c’est un travail comportant autant d’erreur que le site ou il est afficher. It’s jock, just smile and good day Reply

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Оцените статью