Python | Check if all elements in a List are same

Given a list, write a Python program to check if all the elements in given list are same.

Example:

Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
Output: Yes

Input: ['Geeks', 'Is', 'all', 'Same', ]
Output: No

There are various ways we can do this task. Let’s see different ways we can check if all elements in a List are same.

Method #1: Comparing each element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if all 
# ments in a List are same 
  
def ckeckList(lst):
  
    ele = lst[0]
    chk = True
      
    # Comparing each element with first item 
    for item in lst:
        if ele != item:
            chk = False
            break;
              
    if (chk == True): print("Equal")
    else: print("Not equal")            
  
# Driver Code
lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
ckeckList(lst)

chevron_right


Output:



Equal

 
But In Python, we can do the same task in much interesting ways.

Method #2: Using all() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if all 
# elements in a List are same 
res = False
  
def chkList(lst):
    if len(lst) < 0 :
        res = True
    res = all(ele == lst[0] for ele in lst)
      
    if(res):
        print("Equal")
    else:
        print("Not equal")
  
# Driver Code        
lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']
chkList(lst)

chevron_right


Output:

Equal

 
Method #3: Using count() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if all 
# elements in a List are same 
res = False
  
def chkList(lst):
    if len(lst) < 0 :
        res = True
    res = lst.count(lst[0]) == len(lst)
      
    if(res):
        print("Equal")
    else:
        print("Not equal")
  
# Driver Code        
lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']
chkList(lst)

chevron_right


Output:

Equal

 
Method #4: Using set data structure
Since we know there cannot be duplicate elements in a set, we can use this property to check whether all the elements are same or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if all 
# elements in a List are same 
  
def chkList(lst):
    return len(set(lst)) == 1
  
  
# Driver Code        
lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']
  
if chkList(lst) == True: print("Equal")
else: print("Not Equal")

chevron_right


Output:

Equal


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.