0

I am struggling to write a program that will determine if there are only numbers in a list, so floats or integers. Nothing special like "True" is 1 or the ASCII code of "A" or anything like that. I want to check the list to make sure it only has floats or integers. This is my code so far but it doesn't work for all cases.

list1 = [-51,True]
for i in list1:
    if (isinstance(i,int))==False and (isinstance(i,float)==False):
        print("None")

In this case it doesn't print "None". When it should for "True". Any ideas?

  • Does this answer your question? [Comparing boolean and int using isinstance](https://stackoverflow.com/questions/37888620/comparing-boolean-and-int-using-isinstance) – EvanM Apr 08 '20 at 17:36
  • U should change 'and' condition with an 'or'. Because an int is not a float at the same time – Grommy Apr 08 '20 at 17:36

3 Answers3

7

you can use:

all(isinstance(e, (int, float)) for e in list1)
kederrac
  • 16,819
  • 6
  • 32
  • 55
0
import numbers
all(isinstance(x, number.Number) for x in the_list)
Paul Rudin
  • 17
  • 1
  • 7
  • 1
    Is that supposed to be `import numbers`? If so, it doesn't help with booleans: `isinstance(False, numbers.Number)` is `True` – Mark Apr 08 '20 at 17:42
  • ah, yeah. Fixed the typo. In Python `bool` is a subclass of `int`. I guess just `isinstance(x, (float, int))` does it if that's what's wanted although there are other numberish types like `complex` – Paul Rudin Apr 09 '20 at 20:57
0

Found problems with the following approaches for logical type.

mylist = ["name", 6, True]
types = []
for i in mylist:
    types.append(isinstance(i, (int,float,complex)))


#checking whether it has two types or all aren't a number    
if len(set(types))>1 or sum(types)==0:
    print("it hasn't only numbers")   
else:
    print("it has only numbers")

mylist_2 = [7, 6, 2]
types = []

for i in mylist_2:
    types.append(isinstance(i, (int,float,complex)))

if len(set(types))>1 or sum(types)==0:
    print("it hasn't only numbers")   
else:
    print("it has only numbers")       


#approach 2 from other answer:
list1 = [True,False,True]
all(isinstance(e, (int, float)) for e in list1) #True