Change language

Python — Split heterogeneous list of types

|

Method # 1: Using List Comprehension + isinstance()
A combination of the above both functions can be used to accomplish this task. In this case, we simply extract similar element types using different lists and define the type using isinstance ().

# Python3 code to demonstrate how it works
# Split dissimilar type list
# use comprehension list + isinstance

 
# initialize the list

test_list = [ ’gfg’ , 1 , 2 , ’is’ , ’ best’ ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# Split dissimilar type list
# use comprehension list + 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 )]

 
# print 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] Str ing list: [’gfg’,’ is’, ’best’] 

Method # 2: Using defaultdict () + loop
This is another way to solve this problem. In this, we initialize the list as a datatype for defaultdict () and iterate over each element and store each datatype in the defaultdict.

Output:

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

# Python3 code to demonstrate how it works
# Split the dissimilar type list
# using defaultdict () + loop

from collections import defaultdict

 
# initialize list

test_list = [ ’ gfg’ , 1 , 2  , ’is’ , ’ best’ ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Split list of dissimilar types
# using defaultdict () + loop

res = defaultdict ( list )

for ele in test_list:

  res [ type (ele)]. append ( ele)

 
# print result

print ( "Integer list:" + str (res [ int ]))

print ( "String list:" + str (res [ str ]))