I have list with different types of data (string, int, etc.). I need to create a new list with, for example, only int elements, and another list with only string elements. How to do it?
Asked
Active
Viewed 1.3k times
6
-
use `for` loop and `isinstance(element, int)`, etc. – furas Oct 03 '16 at 04:41
-
And you might want to try the `filter` method, or list comprehension – OneCricketeer Oct 03 '16 at 04:41
2 Answers
15
You can accomplish this with list comprehension:
integers = [elm for elm in data if isinstance(elm, int)]
Where data
is the data. What the above does is create a new list, populate it with elements of data
(elm
) that meet the condition after the if
, which is checking if element is instance of an int
. You can also use filter
:
integers = list(filter(lambda elm: isinstance(elm, int), data))
The above will filter out elements based on the passed lambda, which filters out all non-integers. You can then apply it to the strings too, using isinstance(elm, str)
to check if instance of string.

Andrew Li
- 55,805
- 14
- 125
- 143
-
-
-
@EgorOsaulenko Yes, booleans in Python are really integers in disguise. True is 1, False is 0. – Andrew Li Oct 19 '20 at 17:29
-
integers = [elm for elm in data if isinstance(elm, int) and not isinstance(elm, bool)] – Egor Osaulenko Oct 19 '20 at 17:43
-
Not so long developing with python myself (came from c#) and this one was a surprise. I mean - yes, during the implementation of bool it looked suitable, but nowadays.. – Egor Osaulenko Oct 19 '20 at 17:45
1
Sort the list by type, and then use groupby
to group it:
>>> import itertools
>>> l = ['a', 1, 2, 'b', 'e', 9.2, 'l']
>>> l.sort(key=lambda x: str(type(x)))
>>> lists = [list(v) for k,v in itertools.groupby(l, lambda x: str(type(x)))]
>>> lists
[[9.2], [1, 2], ['a', 'b', 'e', 'l']]

TigerhawkT3
- 48,464
- 6
- 60
- 97
-
The OP seems to want separate lists without sublists, but great answer nonetheless! – Andrew Li Oct 03 '16 at 05:26
-
@AndrewL. - They are still separate. They just don't have handcrafted labels. However, that could easily be accomplished with a dictionary instead, e.g. `lists = {k:list(v) for k,v in itertools.groupby(l, lambda x: str(type(x)))}`. The benefit is, of course, that the names are generated automatically and can be easily organized. – TigerhawkT3 Oct 03 '16 at 05:31