user2909250
user2909250

Reputation: 271

How to check if object is list of type str - python

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.

Upvotes: 4

Views: 5690

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

 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

Upvotes: 14

Related Questions