So lets say i have two lists
list1 = [1, "x", 3, "y", 5]
list2 = ["x", "y", "x", "y"]
I would like a function that returns a boolean True for list1 because it contains a few ints and a boolean False for list2 because it contains only strings.
CodePudding user response:
def is_not_all_strings(lst):
return not all(isinstance(k,str) for k in lst)
Or, depending on the need:
def contains_an_integer(lst):
return any(isinstance(k,int) for k in lst)
CodePudding user response:
If you want to capture all kinds of numeric values, not just integers, you can use numbers.Number
, like this:
import numbers
def has_numbers(items):
return any(isinstance(item, numbers.Number) for item in items)
This will detect not just integers but also floats, decimals, fractions etc.
CodePudding user response:
def contains_num(l):
return any(list(map(lambda x:isinstance(x,int),l)))
CodePudding user response:
Use a for
loop. That way, you can return True
once you find one integer and avoid iterating through the remaining elements.
def foo(lst):
for x in lst:
if isinstance(x, int):
return True
return False