Python: Check if List Elements are Numbers

In Python, you can use the isinstance() function to determine if an element is a number type. The specific code is as follows:

my_list = [1, 2, "apple", 3.5, "banana"]
for item in my_list:
    if isinstance(item, (int, float)):
        print(f"{item} is a number")
    else:
        print(f"{item} is not a number")

The code above will iterate through each element in the list “my_list” and then use the isinstance() function to check if the element is an integer or float type. If it is a numerical type, it will output that the number is a digit, otherwise it will output that the element is not a number.

bannerAds