Home > database >  How to separate a list into two lists according to the objects' types using isinstance()?
How to separate a list into two lists according to the objects' types using isinstance()?

Time:10-05

With a list like this: ["apple", "orange", 5, "banana", 8, 9]

How can I put the string(str) in one list and put integer(int) in another list using isinstance()?

CodePudding user response:

This way -

a = ["apple", "orange", 5, "banana", 8, 9]

b1 = [el for el in a if isinstance(el, str)]
b2 = [el for el in a if isinstance(el, int)]

CodePudding user response:

Use list comprehensions:

lst = ["apple", "orange", 5, "banana", 8, 9]
strings = [s for s in lst if isinstance(s, str)]
integers = [n for n in lst if isinstance(n, int)]

Or, to avoid using two for loops, you could also just loop over the list and append to the respective lists as needed:

strings = list()
integers = list()

for l in lst:
    if isinstance(l, str):
        strings.append(l)
    elif isinstance(l, int):
        integers.append(l)

CodePudding user response:

Here is a generic solution using itertools.groupby and type.

I chose here to return a dictionary as it is easy to get elements by name, but you could also return a list of lists.

from itertools import groupby

l = ["apple", "orange", 5, "banana", 8, 9]

grouper = lambda x: type(x).__name__

{k:list(g) for k,g in groupby(sorted(l, key=grouper), grouper)}

output:

{'int': [5, 8, 9], 'str': ['apple', 'orange', 'banana']}

as lists:

ints, strings = [list(g) for k,g in groupby(sorted(l, key=grouper), grouper)]

output:

>>> ints
[5, 8, 9]
>>> strings
['apple', 'orange', 'banana']
  • Related