Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

types

list

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.

like image 297
user2909250 Avatar asked Oct 21 '25 11:10

user2909250


1 Answers

 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

like image 168
Padraic Cunningham Avatar answered Oct 24 '25 00:10

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!