Python - Splitting List That Contains Strings and Integers
As others have mentioned in the comments, you should really start thinking about how you can get rid of the list which holds in-homogeneous data in the first place. However, if that really can't be done, I'd use a defaultdict:
from collections import defaultdict
d = defaultdict(list)
for x in myList:
d[type(x)].append(x)
print d[int]
print d[str]
You can use list comprehension: -
>>> myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
>>> myIntList = [x for x in myList if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']
def filter_by_type(list_to_test, type_of):
return [n for n in list_to_test if isinstance(n, type_of)]
myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
nums = filter_by_type(myList,int)
strs = filter_by_type(myList,str)
print nums, strs
>>>[4, 1, 3] ['a', 'b', 'c', 'd']