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
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
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...
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]
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)]