Skip to content Skip to sidebar Skip to footer

How To Separate Data Types From List?

I'm having trouble trying to separate string and int/float from a single array. So far I could only find methods to remove/extract from list with specific string or number but not

Solution 1:

Python has the isinstance() function to check if objects are of given type.
Btw your given list is not correct !

>>> l = [1, 2, 3, 'a', 4, 11, 212, 'a', 'b', 'c', 3, 32, 4, 'd', 'e']
>>> [item for item in l if isinstance(item, str)]
['a', 'a', 'b', 'c', 'd', 'e']

Solution 2:

You can use the type() function to distinguish between the different data types.


Solution 3:

You can use:

a = [1,2,3,'a',4,11,212,'a','b','c',3,32,4,'d','e']
[x for x in a if type(x)==str]

Output is:

['a', 'a', 'b', 'c', 'd', 'e']

Solution 4:

There are many ways to achieve this scenario, You can use idiomatic way too,

a = [1,2,3,'a',4,11,212,'a','b','c',3,32,4,'d','e']

print [item for item in a if type(item) is str]

Output list: ['a', 'a', 'b', 'c', 'd', 'e']

Post a Comment for "How To Separate Data Types From List?"