0

how can I check the type of all the elements in a list?

For example I have a list:

li = ["Hello", 12121, False]

How can I make a program that goes through each element in a list and outputs the type of each element

Such as "Hell" is a string

12121 is a integer

False is a boolean.

user2891763
  • 413
  • 3
  • 7
  • 12

1 Answers1

0

Check out Python's built-in isintance method, and also the type method. To find out for the whole list, you could simply iterate through the list and output the resultant of the type method.

For example:

for item in list:
    print type(item)

Or if you are expecting certain types:

for item in list:
    if isinstance(item,basestring):
        print "I am a type of string!"
    if isinstance(item,(str,unicode)):
        print "I am a str or unicode!"
    if isinstance(item,int):
        print "I am a type of int!"
    if isinstance(item,(int,float)):
        print "I am an int or a float!"
    if isinstance(item,bool):
        print "I am a boolean!"
    if isinstance(True,bool):
        print "I am a boolean!"
    if isinstance(True,int):
        print "I am an int!"  # because booleans inherit from integers ;)

The isinstance method is usually better because it checks against inherited classes. See this post for a detailed discussion.

Community
  • 1
  • 1
Farmer Joe
  • 6,020
  • 1
  • 30
  • 40
  • @user2891763 You can use a tuple for the argument in `isinstance` to compare against multiple types. I made an edit to demonstrate. – Farmer Joe Oct 31 '13 at 18:16