Tekheny Ghemor Tekheny Ghemor - 6 months ago 13
Python Question

How to check if all items in list are string

If I have a list in python, is there a function to tell me if all the items in the list are strings?

For Example:

["one", "two", 3]
would return
False
, and
["one", "two", "three"]
would return
True
.

Answer

Just use all() and check for types with isinstance().

>>> l = ["one", "two", 3]
>>> all(isinstance(item, str) for item in l)
False
>>> l = ["one", "two", '3']
>>> all(isinstance(item, str) for item in l)
True
Comments