-2

I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?

For example:

[1,2,3] would be true.

["a",2,3] would be false.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Ian
  • 29
  • 2
  • 6
  • Why do you need this? It may be better to handle exceptions instead. See http://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain – Peter Wood Oct 01 '16 at 23:45
  • 1
    In my opinion, you should have tried to write some code first and posted your failed attempt. SO is not a code-writing service. – Terry Jan Reedy Oct 02 '16 at 01:02

3 Answers3

6

You could do this using all, which would short circuit once a false condition is met.

>>> my_list = [1, 2, 3]
>>> all(type(d) == int for d in my_list)
True

>>> my_list = ['1', 2, 3]
>>> all(type(d) == int for d in my_list)
False

isinstance could be used when calling all as well:

>>> my_list = [1, 2, 3]
>>> all(isinstance(d, int) for d in my_list)
True

>>> my_list = ['1', 2, 3]
>>> all(isinstance(d, int) for d in my_list)
False
idjaw
  • 25,487
  • 7
  • 64
  • 83
3

You can use a combination of any() and isinstance():

In [1]: def contains_string(l):
    ...:     return any(isinstance(item, basestring) for item in l)
    ...: 

In [2]: contains_string([1,2,3])
Out[2]: False

In [3]: contains_string(['a',2,3])
Out[3]: True

basestring handles both "unicode" and "str" string types:

Note that any() would short-circuit as well once it knows the result, see more about that here:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

Assuming you meant that you need to check through all the values of the list and that only if they were all integers the function would return True, this is how I'd do it:

def test(list):
    result=True
    for elem in list:
        if type(elem)!=int:
            result=False
    return result
maze88
  • 850
  • 2
  • 9
  • 15