4

Say I have the following objects.

    d = ["foo1", "foo2", "foo3", "foo4"]

    c = 1

    a = ["foo1", 6]

I want to check to see if the object is a list of a certain type. If i want to check to see if d is a list and that list contains strings, how would i do that?

d should pass, but c and a should fail the check.

2
  • specifically list? Should ("foo", "bar", "baz") fail as well? Or even a str, e.g., "foobar", which is technically iterable as well? Commented Jun 13, 2014 at 1:13
  • 1
    I think you should take a look at this SO question because checking for types is very often not what you want to do in Python. Commented Jun 13, 2014 at 1:17

1 Answer 1

14
 d = ["foo1", "foo2", "foo3", "foo4"]
 print isinstance(d,list) and all(isinstance(x,str) for x in d)
 True
 d = ["foo1", "foo2", 4, "foo4"]
 print isinstance(d,list) and all(isinstance(x,str) for x in d)
 False

If d is a list and every element in d is a string it will return True. You can check int, dict, etc.. with isinstance

Sign up to request clarification or add additional context in comments.

1 Comment

should really use basestring if you want to count unicode as strings also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.