Python list all elements same

Check if all elements in a List are same

In this article, we will learn to check that all elements in a list are the same or not in Python. We will use some built-in functions, simple algorithms, and some custom code as well to better understand the problem. Let’s first have a quick look over what is a list in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

list1 = ["Ram", "Arun", "Kiran"] list2 = [16, 78, 32, 67] list3 = ["apple", "mango", 16, "cherry", 3.4]

Python supports many built-in functions to perform this task. We will look at the following ways in which we can check if all the elements present in a list are equal or not.

  1. Using all() function
  2. Using set data type
  3. Using count() function
  4. Using Brute Force Approach
  5. By multiplying elements
  6. Using Slicing method
  7. Using itertools module

Example: Check all List by Using all() Function

This example uses built-in all() function. This the simplest and most elegant way to check for condition but a bit slower than other functions. This function even works with the empty list because this is one of the few cases where python has lazy semantics. In the given example, all() function first convert the input list into iterable and then compares each element of the given list and check if they are equal or not. The program will print ‘Equal’ if all elements are the same else it will print ‘Not Equal’.

r = False def check(l): if(len(l) < 0): r = True r = all(ele == l[0] for ele in l) if(r): print("Equal") else: print("Not Equal") #input list list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call check(list1) check(list2)

Example: Check all List by Using set() Function

This example uses a built-in Python set datatype. Set does not allow duplicate elements. It also requires all of your elements to be hashable. Using this property of set, we can check whether all the elements in a list are the same or not. In this example, the list is converted to a set by passing the list name to set() method as shown below. Set will check for each element and if all the elements in the original list are identical then the set will have just one unique element. The program will return 'Not Equal' if your list has different elements else it will return 'Equal'.

def check(l): return len(set(l)) == 1 #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #check for condition if(check(list1) == True): print("Equal") else: print("Not Equal") if(check(list2) == True): print("Equal") else: print("Not Equal")

Example: Check all List by Using count() Function

This example uses count() function. This method is faster than using set() because the set method works on sequences, not iterables but count() function simply counts the first element. This method needs to really check all elements to get the correct count. This function assumes the list is a non-empty list. In this example, two functions (count,len) are used and both have an easy implementation.

Читайте также:  Html forms templates with css

Therefore, if we have the same element repeated in the list then the length of the list using len() will be equal to the number of times the element is present in the list using the count().

r = False def check(l): if(len(l) < 0): r = True r = l.count(l[0]) == len(l) if(r): print("Equal") else: print("Not Equal") #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call check(list1) check(list2)

Example: Check all List by Using Brute Force Approach

This algorithm uses a simple understandable code of comparing each element of a list using for loop. In this example, the first element of the list is stored in a variable. Then, using for loop each element is compared with the first variable (first element) and if the loop encounters that both elements are not equal then the loop will stop and prints 'Not Equal' else if all the elements are equal to the first variable then the program prints 'Equal'.

def check(l): #stores first element in a variable first = l[0] x = True #Comparing each element with first item for ele in l: if(first != ele): x = False break; if(x == True): print("Equal") else: print("Not Equal") #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call check(list1) check(list2)

Example: Check all List By multiplying the elements

This method is an alternative method and it is faster than the set method. It is a one-liner code. In this example, the program takes the first element and multiply it with the length of the given list to form a new list. So that the new list contains identical elements to the first elements of the given list size, and then compare it with the given list. This method returns True if elements are equal else False.

def check(l): return l and [l[0]]*len(l) == l #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call print(check(list1)) print(check(list2))

Example: Check all List by Using the Slicing method

This example uses the List Slicing operation where a list is sliced depending upon the index passed and a subset of values is retrieved. In this example, we compare the start of the list denoted by [1:] to the end of the list denoted by [:-1] . This method returns True if elements are equal else False.

def check(l): return l[1:] == l[:-1] #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call print(check(list1)) print(check(list2))

Example: Check all List by Using itertools Module

This method uses groupby() function from itertools module. This function has a few properties that make it different from others. It will stop consuming items from the iterable as soon as it finds the first non-equal item. It does not require items to be hashable. It is lazy and only requires O(1) additional memory to do the check. This method returns True if elements are equal else False.

#import groupby function from itertools import groupby def check(iterable): x = groupby(iterable) return next(x, True) and not next(x, False) #input lists list1 = ['bat', 'bat', 'bat', 'bat'] list2 = [1, 3, 7, 1] #function call print(check(list1)) print(check(list2))

Conclusion

In this article, we learned to check whether all elements in the list are the same or not by using several built-in functions such as all() , groupby() , count() and other alternate methods. We used some custom codes as well. We learned about the differences between these methods in terms of processing speed.

Читайте также:  Div html css примеры

Источник

Python : Check if all elements in a List are same or matches a condition

In this article we will dicuss different ways to check if all element in a given List are same or matches a condition.

Suppose we have a list of string i.e.

# List of string listOfStrings = ['Hello'] * 10

Now let’s use python all() function to check if all elements in the given list are same.

Python : all() function

Python all() function checks if all Elements of given Iterable is True.

Frequently Asked:

check if element are same using all()

Let’s convert the list to Iterable and check if each entry of iterable is equal to first element of list using all() i.e.

''' check if element are same using all() It will Iterate through all the elements in list and check if all elements are similar to first element or not. ''' result = False; if len(listOfStrings) > 0 : result = all(elem == listOfStrings[0] for elem in listOfStrings) if result : print("All Elements in List are Equal") else: print("All Elements in List are Not Equal")

Check if all elements are same using list.count()

count() returns the occurrence count of given element in the list.

Let’s call the count() function of list with firts element of list as argument. If its occurrence count is equal to the length of list, then it means all elements in list are Same i.e.

''' check if element are same using list.count() If occurence count of first element in list is equal to length of list. Then it means all elements in List are equal ''' result = False; if len(listOfStrings) > 0 : result = listOfStrings.count(listOfStrings[0]) == len(listOfStrings)

Let’s do the same thing in single line i.e.

result = len(listOfStrings) > 0 and all(elem == listOfStrings[0] for elem in listOfStrings)

Check if all elements are same using Set

As set contains only unique elements, so convert the list to set. If set size is 1 then it means all elements in given list are same i.e.

''' As set contains unique elements only, so if list has similar elements, then only one will stored in set. ''' result = len(set(listOfStrings)) == 1

Complete example is as follows,

def main(): # List of string listOfStrings = ['Hello'] * 10 # Print the List print(listOfStrings) ''' check if element are same using all() It will Iterate through all the elements in list and check if all elements are similar to first element or not. ''' result = False; if len(listOfStrings) > 0 : result = all(elem == listOfStrings[0] for elem in listOfStrings) if result : print("All Elements in List are Equal") else: print("All Elements in List are Not Equal") ''' check if element are same using list.count() If occurence count of first element in list is equal to length of list. Then it means all elements in List are equal ''' result = False; if len(listOfStrings) > 0 : result = listOfStrings.count(listOfStrings[0]) == len(listOfStrings) if result : print("All Elements in List are Equal") else: print("All Elements in List are Not Equal") # Do the above logic in single line result = len(listOfStrings) > 0 and all(elem == listOfStrings[0] for elem in listOfStrings) if result : print("All Elements in List are Equal") else: print("All Elements in List are Not Equal") ''' As set contains unique elements only, so if list has similar elements, then only one will stored in set. ''' result = len(set(listOfStrings)) == 1 if result : print("All Elements in List are Equal") else: print("All Elements in List are Not Equal") if __name__ == '__main__': main()
['Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello'] All Elements in List are Equal All Elements in List are Equal All Elements in List are Equal All Elements in List are Equal

Источник

Читайте также:  Javascript document forms this

Python - Check if all elements in a List are same

Sometimes we come across the need to check if we have one single value repeated in a list as list elements. We can check for such scenario using the below python programs. There are different approaches.

Using for Loop

In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false.

Example

List = ['Mon','Mon','Mon','Mon'] result = True # Get the first element first_element = List[0] # Compares all the elements with the first element for word in List: if first_element != word: result = False print("All elements are not equal") break else: result = True if result: print("All elements are equal")

Running the above code gives us the following result −

All elements are equal All elements are equal All elements are equal All elements are equal

Using All()

The all() method applies the comparison for each element in the list. It is similar to what we have done in first approach but instead of for loop, we are using the all() method.

Example

List = ['Mon','Mon','Tue','Mon'] # Uisng all()method result = all(element == List[0] for element in List) if (result): print("All the elements are Equal") else: print("All Elements are not equal")

Running the above code gives us the following result −

All the elements are not Equal

Using Count()

The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.

Example

List = ['Mon','Mon','Mon','Mon'] # Result from count matches with result from len() result = List.count(List[0]) == len(List) if (result): print("All the elements are Equal") else: print("Elements are not equal")

Running the above code gives us the following result −

All the elements are Equal

Источник

Оцените статью