Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the simple way to check if the elements of a list or set are single type?

Tags:

python

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.

like image 677
Max Avatar asked Nov 30 '22 23:11

Max


1 Answers

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).

like image 65
eumiro Avatar answered Dec 05 '22 01:12

eumiro