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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read