i need to write a piece of code if all the elements are int or all are string then return true,else return false
[1,'1','a','b'] False
[1,2,3,4] True
['apple','orange','melon'] True
['1', 2, 3, 4] False
my solution is these
def foo(l):
t = type(l[0])
if t is not str and t is not int:
return False
for x in l:
if t != type(x):
return False
return True
i think it should be better.
This code checks generally if all elements are of the same type:
len(set(type(elem) for elem in elems)) == 1
It answers the title of your question, but works differently than your solution (which returns false for a list of floats).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With