pythonlisttuplesisinstance

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


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()?


Solution

  • 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)