3
def intLst(list):
    nlst=[]
    for index1 in int(len(list)):
        for index2 if int(len(list[index1])):
               list[index1][index2].isdigit()
     return nlst

What am I doing wrong? I need to find the int in lst

  • The irony is that everyone who has been doing this for a bit is suggesting list comprehensions but as @Ann Zen points out this might be a step too for you at this point. That should tell you how central they'll be. – hrokr Nov 10 '20 at 02:27

3 Answers3

3

You can easily do this using a list comprehension!

lst = [['five',6,7.7], ['eight','ten', 3.4, 8] , ['one', 9.5]]

def intList(lst: list) -> list:
    return [x for i in lst for x in i if type(x) == int]

print(intList(lst))
[6, 8]

For every nested list in a list i, for every item in that sublist, if the item's type is an integer: append it to a list

Please note that in your original code using list as a parameter, function, or variable name is NOT advised...

Ironkey
  • 2,568
  • 1
  • 8
  • 30
  • So if I did most.append(int(val)) would that be ok? –  Nov 10 '20 at 02:19
  • instead of directly going to return creating a for loop –  Nov 10 '20 at 02:20
  • Yes, that would work perfectly fine, if you have any problems you can ask. @Ann Zen 's expanded answer shows the expanded version of this very well! – Ironkey Nov 10 '20 at 04:59
1

The answer given by @Ironkey is the way to go! If you are just starting with python and want to better understand your for-loops better before you dive into list comprehensions. The explanations are commented in the code:

def intLst(list):
    nlst=[]
    for index1 in range(len(list)): # len() if used properly, will *always* return an integer, so adding the int() is redundant 
        for index2 in range(len(list[index1])): # Also, integers aren't subscriptable, you will need range()
            if type(list[index1][index2]) == int: # isdigit() will only work on strings, using it on an actual integer will return an error
                nlst.append(list[index1][index2])
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))

But with python, you can directly iterate through each list, without using indices:

def intLst(lst):
    nlst=[]
    for value1 in lst:
        for value2 in value1:
            if type(value2) == int:
                nlst.append(value2)
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))

These will both print:

[6,8]
Ironkey
  • 2,568
  • 1
  • 8
  • 30
Red
  • 26,798
  • 7
  • 36
  • 58
0

You have multiple errors like that you are using for..if instead of for..in, also having just returning boolean values, so you can fix it with a list comprehension like this (Don't take list as variable NAME!!):

def intLst(myList):
  return [item for sublist in myList for item in sublist if isinstance(item,int)]
Wasif
  • 14,755
  • 3
  • 14
  • 34