Python - Split heterogeneous type list
Last Updated :
17 May, 2023
Sometimes, we might be working with many data types and in these instances, we can have a problem in which list that we receive might be having elements from different data types. Let's discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isinstance()
The combination of above both functionalities can be used to perform this task. In this, we just extract the similar element types using different list comprehensions and detect the type using isinstance().
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using list comprehension + isinstance
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using list comprehension + isinstance
res_str = [ele for ele in test_list if isinstance(ele, str)]
res_int = [ele for ele in test_list if isinstance(ele, int)]
# printing result
print("Integer list : " + str(res_int))
print("String list : " + str(res_str))
Output : The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using list comprehension + isinstance() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of string list.
Method #2 : Using defaultdict() + loop
This is yet another way in which this problem can be solved. In this, we initialize the list as data type for defaultdict() and loop through each element and save each datatype list in defaultdict.
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using defaultdict() + loop
from collections import defaultdict
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using defaultdict() + loop
res = defaultdict(list)
for ele in test_list:
res[type(ele)].append(ele)
# printing result
print("Integer list : " + str(res[int]))
print("String list : " + str(res[str]))
Output : The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3: Using filter() and lambda function
Use the filter() function with a lambda function to split the heterogeneous list into two lists containing only integers and strings, respectively.
Step-by-step approach:
- Initialize the original list.
- Use the filter() function with a lambda function to create two lists, one containing only integers and the other containing only strings.
- Convert the filtered objects into lists.
- Print the resulting integer and string lists.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using filter() + lambda function
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using filter() + lambda function
res_int = list(filter(lambda x: isinstance(x, int), test_list))
res_str = list(filter(lambda x: isinstance(x, str), test_list))
# printing result
print("Integer list : " + str(res_int))
print("String list : " + str(res_str))
OutputThe original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
Time complexity: O(n), where n is the length of the original list. Therefore, the overall time complexity of this method is O(n).
Auxiliary space: O(n) because two new lists are created to store the filtered elements.
Method #4: Using recursive method :
Algorithm:
- Define a function split_list(lst) that takes the input list lst as an argument.
- If the length of the input list lst is 0 or 1, then return the input list as it is since there is no need to split it further.
- Otherwise, split the input list lst into two parts by creating two empty lists res_int and res_str.
- Iterate over each element elem in the input list lst.
- If the current element elem is an integer, then append it to the res_int list.
- If the current element elem is a string, then append it to the res_str list.
- Recursively call the split_list() function with the first half of the input list as the argument and store the
- returned result in a variable left_list.
- Recursively call the split_list() function with the second half of the input list as the argument and store the
- returned result in a variable right_list.
- Concatenate left_list and right_list to get the final result and return it.
Python3
def split_list(test_list):
if not test_list:
return [], []
elif isinstance(test_list[0], int):
res_int, res_str = split_list(test_list[1:])
return [test_list[0]] + res_int, res_str
else:
res_int, res_str = split_list(test_list[1:])
return res_int, [test_list[0]] + res_str
# example usage
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
int_list, str_list = split_list(test_list)
print("Integer list : " + str(int_list))
print("String list : " + str(str_list))
#This code is contributed by Jyothi Pinjala
OutputThe original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
Time Complexity :
The time complexity of this depends on the number of elements in the input list lst and the number of recursive calls made to the split_list() function. In the worst case, the input list is split into two equal halves at each recursive call, resulting in a total of log n recursive calls, where n is the number of elements in the input list. At each recursive call, we iterate over each element of the input list once. Therefore, the time complexity of this algorithm is O(n * log n), where n is the number of elements in the input list.
Auxiliary Space:
The space complexity of this depends on the number of recursive calls made to the split_list() function. In the worst case, the input list is split into two equal halves at each recursive call, resulting in a total of log n recursive calls, where n is the number of elements in the input list. Each recursive call creates two new lists res_int and res_str, which can each hold up to n/2 elements. Therefore, the space complexity of this algorithm is O(n * log n), where n is the number of elements in the input list.
Similar Reads
Python | Convert heterogeneous type String to List
Sometimes, while working with data, we can have a problem in which we need to convert data in string into a list, and the string contains elements from different data types like boolean. This problem can occur in domains in which a lot of data types are used. Let's discuss certain ways in which this
6 min read
How to Split Lists in Python?
Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read
Python | Split list in uneven groups
Sometimes, while working with python, we can have a problem of splitting a list. This problem is quite common and has many variations. Having solutions to popular variations proves to be good in long run. Let's discuss certain way to split list in uneven groups as defined by other list. Method 1: Us
6 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python | Custom list split
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let's discuss certain ways in which this task can be performed. Method
8 min read
Python | Find Min/Max in heterogeneous list
The lists in Python can handle different type of datatypes in it. The manipulation of such lists is complicated. Let's say we have a problem in which we need to find the min/max integer value in which the list can contain string as a data type i.e heterogeneous. Let's discuss certain ways in which t
7 min read
Python - Split in Nested tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let's discuss certain ways in which this task can be performed. Input : test_
7 min read
Python - Integers String to Integer List
In this article, we will check How we can Convert an Integer String to an Integer List Using split() and map()Using split() and map() will allow us to split a string into individual elements and then apply a function to each element. Pythons = "1 2 3 4 5" # Convert the string to a list of integers u
2 min read
Python | Summation of integers in heterogeneous list
Sometimes, while working with Python, we can come across a problem in which we require to find the sum of list. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let's discuss certain ways in which this task can be performed. Method
6 min read
How To Slice A List Of Tuples In Python?
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read