Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Split list into lists by particular value

Python | Split list into lists by particular value

In Python, To split a list into sublists based on a particular value. The idea is to iterate through the original list and group elements into sub-lists whenever the specified value is encountered. It is often necessary to manipulate and process lists, especially when dealing with large amounts of data. One frequent operation is dividing a list into several sub-lists according to a specific value. When you wish to combine components together or analyze different subsets of the data, this procedure might be helpful.

Ways to Split Lists into Lists Based on Condition

Here are the different methods we can use to split lists into lists based on the given condition.

  • Using Simple Iteration
  • Using list comprehension
  • Using for loops
  • Using Recursion
  • Using Itertools
  • Using NumPy

Split list in Python using Iteration

In Python, we will split a list into lists by particular value using Simple iteration. The code initializes a list and a particular value. It then splits the list into sublists based on the particular value by iterating over each element of the list.

Python3




test_list = [1, 4, 5, 6, 4, 5, 6, 5, 4]
 
print("The original list : " + str(test_list))
 
particular_value = 5
result = []
temp_list = []
for i in test_list:
    if i == particular_value:
        temp_list.append(i)
        result.append(temp_list)
        temp_list = []
    else:
        temp_list.append(i)
result.append(temp_list)
print("The list after splitting by a value : " + str(result))


Output

The original list : [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by a value : [[1, 4, 5], [6, 4, 5], [6, 5], [4]]

Split a Python List into Chunks using List Comprehension

In Python, we will split a list into lists by particular value using List comprehension. This problem can be solved in two parts, in the first part we get the index list by which split has to be performed using enumerate function. And then we can join the values according to the indices using zip and list slicing. 

Python3




test_list = [1, 4, 5, 6, 4, 5, 6, 5, 4]
 
print("The original list : " + str(test_list))
 
# using list comprehension Split list into lists by particular value
size = len(test_list)
idx_list = [idx + 1 for idx, val in
            enumerate(test_list) if val == 5]
 
 
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))


Output

The original list : [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by a value : [[1, 4, 5], [6, 4, 5], [6, 5], [4]]

Split list in Python using For Loops

In Python, we will split a list into lists by particular value using for loops. The code converts the original listing into a string representation and replaces the particular price with a delimiter (*). It then splits the changed string on the delimiter to acquire substrings.

Python3




test_list = [1, 4, 5, 6, 4, 5, 6, 5, 4]
 
print("The original list : " + str(test_list))
 
x = list(map(str, test_list))
x = " ".join(x)
x = x.replace("5", "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))


Output

The original list : [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by a value : [[1, 4, 5], [6, 4, 5], [6, 5], [4]]

Split a list into multiple list using Recursion

In Python, we will split a list into lists by particular value using Recursion. The code defines a recursive function called split_list_recursive that splits a given list into sublists whenever a particular value occurs. It uses recursion and two temporary lists (result and temp_list) to store the resulting sublists.

Python3




def split_list_recursive(test_list, result, temp_list, particular_value):
 
    if not test_list:
        result.append(temp_list)
        return
    if test_list[0] == particular_value:
        result.append(temp_list + [particular_value])
        split_list_recursive(test_list[1:], result, [], particular_value)
    else:
        split_list_recursive(test_list[1:],
                             result,
                             temp_list + [test_list[0]],
                             particular_value)
 
 
test_list = [1, 4, 5, 6, 4, 5, 6, 5, 4]
particular_value = 5
result = []
print("The original list:", test_list)
split_list_recursive(test_list, result, [], particular_value)
print("The list after splitting by value:", result)


Output

The original list: [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by value: [[1, 4, 5], [6, 4, 5], [6, 5], [4]]

Split list in Python using Itertools

In Python, we will split a list into lists by particular value using itertools. The code defines a function called split_list that takes a list and a value as input. It uses the itertools.groupby() function to group consecutive elements in the list based on whether they are equal to the given value.

Python3




import itertools
 
def split_list(lst, val):
    return [list(group) for k,
            group in
            itertools.groupby(lst, lambda x: x==val) if not k]
 
original_lst = [1, 4, 5, 6, 4, 5, 6, 5, 4]
split_lst = split_list(original_lst, 6)
 
print("The original list:", original_lst)
print("The list after splitting by a value:", split_lst)


Output

The original list: [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by a value: [[1, 4, 5], [4, 5], [5, 4]]

Split list in Python using NumPy

In Python, we will split a list into lists by particular value using Numpy. The code takes a list and a particular value as input. It then converts the list into a NumPy array and finds the indices where the particular value occurs. 

Python3




import numpy as np
 
test_list = [1, 4, 5, 6, 4, 5, 6, 5, 4]
particular_value = 5
 
arr = np.array(test_list)
 
idx = np.where(arr == particular_value)[0]
 
subarrays = np.split(arr, idx+1)
 
result = [subarray.tolist() for subarray in subarrays if len(subarray) > 0]
 
print("The original list:", test_list)
print("The list after splitting by a value:", result)


Output

The original list: [1, 4, 5, 6, 4, 5, 6, 5, 4]
The list after splitting by a value: [[1, 4, 5], [6, 4, 5], [6, 5], [4]

RELATED ARTICLES

Most Popular

Recent Comments