0

I am learning data structures and algorithms and decided to start up a quick code for separating a list into data types. My goal is to have a loop that checks each value in a list and then have if statements to determine whether it's an int, bool, string, or float. I am not sure why, but something with the conditional statements is off because it runs my final "else" statement.

myList = ['test',3,True,'chicken',False,95,33/4,.02,'rabbit',False]
myInts = []
myBools = []
myStrings = []
myFloats = []

for a in myList:
  if a == int:
    myInts.append(a)
  elif a == bool:
    myBools.append(a)
  elif a == str:
    myStrings.append(a)
  else:
    myFloats.append(a)

print('Ints:', myInts)
print('Bools:',myBools)
print('Strings:',myStrings)
print('Floats:',myFloats)
  • 1
    A number will never be `int`, `bool`, `str`, `float`, or `str`. Those are types, and values are not equal to their types. Use `type(a) is int` and so on. – kindall Nov 30 '17 at 16:38
  • 3
    Rather, use `isinstance(a, bool)` etc. – Daniel Roseman Nov 30 '17 at 16:38
  • 2
    Possible duplicate of [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – mkrieger1 Nov 30 '17 at 16:47

2 Answers2

1

You need to use type(x) in order to determine the type. But what you really want to do is use: isinstance(a, int). Where you can change the second argument to be any type such as str, bool, etc.

DSCH
  • 2,146
  • 1
  • 18
  • 29
0

You can use a shortcut way, also using isinstance method, to get every type in a separated list as

myStrings=[s for s in myList if isinstance(s,str)]

and do the same for the other types.

alshaboti
  • 643
  • 8
  • 18