3 Ways to Check if all Elements in List are Same [Python Code]

Method 1: Using Python set:

listChar = ['z','z','z','z']
 
if(len(set(listChar))==1):
  print "All elements in list are same"
else:
  print "All elements in list are not same"

Method 2: Using Python count() function:

listChar = ['z','z','z','z']
 
if listChar.count(listChar[0]) == len(listChar):
  print "All elements in list are same."
else:
  print "Elements in list are different."

Method 3: Using Python all() function:

listChar = ['z','z','z','z']
 
if all(x == listChar[0] for x in listChar):
    print "All elements in list are equal"
else:
    print "All elements in list are not equal"
发布了163 篇原创文章 · 获赞 90 · 访问量 6289

猜你喜欢

转载自blog.csdn.net/weixin_45405128/article/details/104204660