The standard way to check what kind of object you have is by
using the isinstance(object, classinfo) function. Using isinstance(...)
is preferred over type(object) because type(...)
returns the exact type of an object, and does not account for sub-classes when checking types (this is significant in more complex scenarios).
You can check if you have a number (int
, float
, etc.) by comparing each class individually or with numbers.Number:
# Check for any type of number in Python 2 or 3.
import numbers
isinstance(value, numbers.Number)
# Check for floating-point number in Python 2 or 3.
isinstance(value, float)
# Check for integers in Python 3.
isinstance(value, int)
# Check for integers in Python 2.
isinstance(value, (int, long))
You can check if you have a string (str
, bytes
, etc.) by comparing with the individual classes which vary depending on whether you're using Python 2 or 3:
# Check for unicode string in Python 3.
isinstance(value, str)
# Check for binary string in Python 3.
isinstance(value, bytes)
# Check for any type of string in Python 3.
isinstance(value, (str, bytes))
# Check for unicode string in Python 2.
isinstance(value, unicode)
# Check for binary string in Python 2.
isinstance(value, str)
# Check for any type of string in Python 2.
isinstance(value, basestring)
So, putting that all together you'd have:
import numbers
stringList = []
numberList = []
for value in mixedList:
if isinstance(value, str):
stringList.append(value)
elif isinstance(value, numbers.Number):
numberList.append(value)