Home > Mobile >  Looking for an way to filter strings out of a mixed list and than return only the int
Looking for an way to filter strings out of a mixed list and than return only the int

Time:11-17

Hello yes this is for a homework help. I just need some guidance to what I'm doing wrong here.

These are the directions: Filter integers

  • Create a function called filter_int() with input parameter list (list) and return value (list of integers)
  • Create a for loop that will filter list to only get (int)
  • Return list of ints -DO NOT USE THE FILTER FUNCTION
  • Example:

filter_int(["hello", 5, 5.0, 6, "World", "Yes", 4, 9.0])

[5, 6, 4]

And what I have got so far:

def filter_int(list):
    list2 = []
    discard = []
    for i in list:
        if i in "qwertyuiopasdfghjklzxcvbnm":
            discard.append(i)
        elif i not in "qwertyuiopasdfghjklzxcvbnm":
            list2.append(i)
    return list2

I got an error on this one when I ran it. I'm kind of new to python so any help would be appreciated.

CodePudding user response:

you can use isinstance method

for i in list:
    if isinstance(i, int):
        list2.append(i)
  • Related