Reputation: 11
I am trying to write a function where it takes a list that contains both numbers and strings and returns only a list containing numbers. The code I have written is shown below, but it keeps throwing an error and I can’t understand what I have done wrong. Hope you can help.
lst = [99, 'no data', 95, 94, 'no data']
def foo(lst):
return [x for x in lst if x.isdigit()]
print(foo(lst))
Upvotes: 1
Views: 87
Reputation: 46
The idea is to check if each of the element's type is int
or not. As mentioned in the comments, isDigit
is not available for elements of type int
.
lst = [99, 'no data', 95, 94, 'no data']
list=[]
def foo(lst):
return [x for x in lst if type(x)==int]
print(foo(lst))
output:
[99, 95, 94]
Upvotes: 0
Reputation: 2823
The error is because the isdigit()
only works on string
lst = [99, 'no data', 95, 94, 'no data']
def foo(lst):
return [lst[x] for x in range(0,len(lst)) if str(lst[x]).isdigit() ]
print(foo(lst))
Output:
[99, 95, 94]
Upvotes: 0
Reputation: 94
lst = [99, 'no data', 95, 94, 'no data']
def isDigit(n):
return type(n) is int
def foo(lst):
return [x for x in lst if isDigit(x)]
print(foo(lst))
Upvotes: 1
Reputation: 51
lst = [99, 'no data', 95, 94, 'no data']
def foo(lst):
return [x for x in lst if type(x)==int]
print(foo(lst))
Upvotes: 0
Reputation: 399
lst = [99, 'no data', 95, 94, 'no data']
def foo(lst):
return [x for x in lst if isinstance(x,str)]
print(foo(lst))
Upvotes: 1
Reputation: 49
lst = [99, 'no data', 95, 94, 'no data']
def foo(lst):
return [x for x in lst if isinstance(x, int)]
print(foo(lst))
Upvotes: 1