Split the heterogeneous type list in Python

The list in Python is a dynamic size array, that can store homogeneous type of data as well as heterogeneous type of data. But sometimes we need to access heterogeneous data separately according to their data types. In this tutorial, we will learn how to split the heterogeneous type of list using python.

Three methods can be used to split the heterogeneous list:

  1. Using type() 
  2.  isinstance()
  3. Using defaultdict()

1. Using type()
The following code shows the simple steps using type() function, for loop and if-else statements to split the heterogeneous type of list in python. type(object) function returns the type of the object passed as a parameter.

res1=[]
res2=[]
list2=['abc','xyz',1,2,'pqr',3,4,'a']
for j in list2:
    if(type(j)==int):
        res1.append(j)
    elif(type(j)==str):
        res2.append(j)
print("Integer list:  " +str(res1))
print("String List: " + str(res2))
Output:

Integer list:  [1, 2, 3, 4]
String List: ['abc', 'xyz', 'pqr', 'a']

2. Using isinstance()
The isinstance() function takes data element (or object) and the data type (or class information) as parameters, and returns True if the data element is of the type specified and if contrary it returns False.

res1=[]
res2=[]

list1=['abc','xyz',1,2,'pqr',3,4,'a']

for i in list1:
    if(isinstance(i,int)):
        res1.append(i)
    elif(isinstance(i,str)):
        res2.append(i)

print("The list of integers"+str(res1))
print("The list of strings:"+str(res2))
Output:

The list of integers[1, 2, 3, 4]
The list of strings:['abc', 'xyz', 'pqr', 'a']

The data element is added to the result list when isinstance() returns True.

3. Using defaultdict()
The defaultdict() function returns an object which is the same as a dictionary, in addition it can take a list, set, etc. to create a dictionary. The defaultdict() is a subclass of dict(), so all the other functionalities are the same.

from collections import defaultdict
list2=['abc','xyz',1,2,'pqr',3,4,'a']
d2=defaultdict(list)

for i in list2:
    d2[type(i)].append(i)
print(d2)
print("The list of integers" + str(d2[int]))
print("The list of strings:" + str(d2[str]))
Output:

defaultdict(<class 'list'>, {<class 'str'>: ['abc', 'xyz', 'pqr', 'a'], <class 'int'>: [1, 2, 3, 4]})
The list of integers[1, 2, 3, 4]
The list of strings:['abc', 'xyz', 'pqr', 'a']

In this code, defaultdict() function creates a dictionary, and append() method of list adds the element to the list of the key which is the datatype of the data element. However, using the dictionary it becomes easy to access the homogeneous elements. This helps to perform the desired formatting and operations.

So, here we conclude that we can split the heterogeneous type of list using various methods as explained in the above post. For detailed study of isinstance() click here and defaultdict() click here.

Leave a Reply

Your email address will not be published. Required fields are marked *