Ruslan
Ruslan

Reputation: 43

How can I write a Python function that will only accept a list with int or float type inside?

I need to write a function which will take a list with int or float types. If there will be a nested list, the function must return "No", and if there will be only float or int types, the function must return "Yes". Here is my code

def take_list(lst):
    for i in lst:
        if isinstance(i, list) is True:
            return "No"
        elif isinstance(i, int) or isinstance(i, float):
            return "Yes"


print(take_list([1, 2, [3, 2]]))
print(take_list([1, 2, 3, 2]))

But here is the answer is always "Yes". I tried "type" instead of "isinstance", so it doesn't work

Upvotes: 0

Views: 1811

Answers (1)

Minions
Minions

Reputation: 5487

what about using type?

def take_list(lst):
    # if all(isinstance(item, (int, float)) for item in lst): # another way
    if all(type(item).__name__ in ['int', 'float'] for item in lst):
        return "Yes"
    else:
        return "No"


print(take_list([1, 2, [3, 2]]))     # No
print(take_list([1, 2, 3, 2, 1.2]))  # Yes

type is a function in int and float classes, use ___name___ to get the classes names.

Upvotes: 1

Related Questions