- How to compare two lists in python?
- 6 Answers 6
- python reduce to check if all elements are equal
- 6 Answers 6
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Python – Check If All Elements in a List are Equal
- How to check if all the list items are the same?
- Examples
- Example 1 – Check if all the list elements are equal using all()
- Example 2 – Check if all list elements are equal using a for loop
- Example 3 – Check if all the list elements are equal using a set
- Summary
- Author
How to compare two lists in python?
Now I want to compare these two lists. I guess split returns a list. We can do simple comparision in Java like dateArr[i] == sdateArr[i] , but how can we do it in Python?
By the way, you might find the datetime type handy if you want to work with times rather than generic lists of strings.
6 Answers 6
a=[1,2,3] b=['a','b'] c=[1,2,3,4] d=[1,2,3] a==b #returns False a==c #returns False a==d #returns True
a = ['a1','b2','c3'] b = ['a1','b2','c3'] c = ['b2','a1','c3'] # if you care about order a == b # True a == c # False # if you don't care about order AND duplicates set(a) == set(b) # True set(a) == set(c) # True
By casting a , b and c as a set, you remove duplicates and order doesn’t count. Comparing sets is also much faster and more efficient than comparing lists.
Its incorrect to turn arrays into sets — it will throw duplicated items, not only remove order. Try to compare arrays [1,2] and [1, 1, 2, 2, 2] with sets.
@DenisBarmenkov I don’t see the problem. Can you point out the problem? Python repl: >>> set([1,2]) == set([1,1,2,2,2]) produces True
Sets contain unique numbers but lists have an order. [1,2] does not equal to [2,1]. Or we have to change topic question. Also you could take a look on likes count :/
l1 = [1,2,3] l2 = [1,2,3,4] l1 == l2 # False
l1 = array('l', [1, 2, 3]) l2 = array('d', [1.0, 2.0, 3.0]) l1 == l2 # True l2 = array('d', [1.0, 2.0, 3.0, 4.0]) l1 == l2 # False
If you want to compare strings (per your comment):
date_string = u'Thu Sep 16 13:14:15 CDT 2010' date_string2 = u'Thu Sep 16 14:14:15 CDT 2010' date_string == date_string2 # False
Now both these dates were string I created array out of that but how do I compare them using for loop?
@Umesh Kacha: Scroll up and look at your question. Below it there are several buttons. The second from the left says edit . This can be used to edit your question, for instance if you want to add additional information.
Given the code you provided in comments, I assume you want to do this:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split() >>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split() >>> dateList == sdataList false
The split -method of the string returns a list. A list in Python is very different from an array. == in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.
python reduce to check if all elements are equal
Suppose a = [[1,2,3],[1,2,3]] reduce(lambda x,y: x==y, a) returns True But if a = [[1,2,3],[1,2,3],[1,2,3]] reduce(lambda x,y: x==y, a) returns False Why in the second case, the outcome is False ? please help thanks
6 Answers 6
Try this instead, it works for lists of any size:
Notice that your proposed solution using reduce doesn’t work for more than two items, as the accumulated value after the first comparison is True , and you’d be comparing True against each of the elements from that point on, and obviously that’s not going to work.
sure. actually I am doing the simpler a[1:] == a[:-1] it works, but my question is why reduce produces unexpected result as shown in my question?
You are not reducing the lists. The return value of your lambda is True or False , which is then used as input parameters to further calls to the same lambda function. So you end up comparing a boolean with a list. Therefore, the reducing function should return the same type as it input parameters.
You were probably looking for what other answers proposed instead: use all() .
You can still use reduce! Check out this magic:
bool(reduce(lambda x,y: (x==y)*x, a))
Since the return value of the lambda for x==y is True or False, that can be multiplied by the input and then used in the next comparison because True*[1,2,3] is [1,2,3] . It also works for strings, True*»MyString» is «MyString» .
Try it. However, this method will not work for a list of zeros.
Because first time reduce compare [1,2,3] == [1, 2, 3] and it’s true next time it compare True and [1,2,3] and it’s false.
Help on built-in function reduce in module __builtin__: reduce(. ) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
a = [range(1, 4), range(1, 4), range(1, 4)]
To evaluate reduce(operator.eq, a) the reduce function will first evaluate the function operator.eq on the first two elements of a to obtain True . Then it will call operator.eq again with True and range(1, 4) as the two arguments, and obtain False which is the final result of reduce .
from functools import partial import operator allequal = reduce(partial(operator.eq, a[0]), a[1:])
Why in the second case, the outcome is False
Because reduce(lambda x, y: x == y, (a, b, c, d)) does not mean (a == b) and (b == c) and (c == d) ; it means (((a == b) == c) == d) . a == b will produce either True or False , which then gets compared to c .
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Python – Check If All Elements in a List are Equal
In this tutorial, we will look at how to check if all the elements in a list are equal or not in Python with the help of some examples.
How to check if all the list items are the same?
You can use the Python built-in all() function to check if all the elements in a list are equal or not by checking if each value is the same as the first value in the list.
The all() function takes in an iterable as an argument and returns True if all the values in the iterable are truthy (represent True in a boolean context).
So, to check if all the values in a given list are the same or not, use the all() function to check if all the values are equal to the first value in the list. The following is the syntax –
# check if all the list values are the same all(val == ls[0] for val in ls)
It returns True if all the values in the list are equal.
Note that there are other methods as well that you can use to check if all list values are the same or not. Some of them are –
- Iterate through the list and keep track of the distinct values you encounter.
- Create a set from list elements and check if its size is one or not.
Examples
Let’s now look at some examples of using the above methods. First, we will create a few lists that we’ll use to demonstrate the methods.
# list with all values same ls1 = [5, 5, 5, 5] # list with more than one unique value ls2 = [1, 2, 3, 4, 5, 5] # empty list ls3 = [] # display the lists print(ls1) print(ls2) print(ls3)
Here, we created three lists – ls1 , ls2 , and ls3 . The list ls1 contains the same value as its elements. The list ls2 has repeated values but not all values are the same and the list ls3 is empty (it does not contain any elements).
Example 1 – Check if all the list elements are equal using all()
The idea here is to use the all() function to check if each list element is equal to the first list element.
You can use a list comprehension to create a list of boolean values – whether a list element is the same as the first list value and then pass this resulting list as an argument to the all() function.
Let’s apply this to the lists ls1 and ls2 created above.
# check if all list values are same print(all([val == ls1[0] for val in ls1])) print(all([val == ls2[0] for val in ls2]))
We get True for ls1 and False for ls2 .
If you apply this method to an empty list, you’ll get True as the output.
all([val == ls3[0] for val in ls3])
Note that the all() takes an iterable as an argument, you can directly use an iterator (without using a list comprehension).
# check if all list values are same print(all(val == ls1[0] for val in ls1)) print(all(val == ls2[0] for val in ls2)) print(all(val == ls3[0] for val in ls3))
We get the same results as above.
Example 2 – Check if all list elements are equal using a for loop
The idea here is to iterate through the list and keep a count of each unique element we encounter. If the resulting count is 1, we can say that all the values in the list are the same (the list has only one unique value).
You can use another list to keep track of the visited elements.
def check_if_list_values_same(ls): visited = [] count = 0 for val in ls: if val not in visited: count += 1 visited.append(val) return count == 1 # check if all list values are same print(check_if_list_values_same(ls1)) print(check_if_list_values_same(ls2)) print(check_if_list_values_same(ls3))
We get True for ls1 and False for ls2 and ls3 . Note that here we get False for an empty list.
If you want True as the output for an empty list, modify the condition in the return statement to count
Example 3 – Check if all the list elements are equal using a set
In this method, we create a set from the list elements and check if the size of the set is equal to one. Since a set only holds unique values, if the list has the same elements, the resulting set will only have one value.
# check if all list values are same print(len(set(ls1)) == 1) print(len(set(ls2)) == 1) print(len(set(ls3)) == 1)
We get True for ls1 and False for ls2 and ls3 . (Same as the above method).
If you want True as the output for an empty list, check if the set length is less than equal to 1.
Summary
In this tutorial, we looked at some different methods to check if all the values in a list are the same or not. The following are the different methods covered –
- Use the Python built-in all() function to check if each list element is equal to the first list element.
- Iterate through the list elements and track the count of unique values encountered.
- Convert the list to a set and check if its size is equal to one.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts