Python – Split heterogeneous type list

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Split heterogenous 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 heterogenous 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))

chevron_right


Output :



The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Split heterogenous 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 heterogenous 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]))

chevron_right


Output :

The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.