Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing all elements of two tuples (with all() functionality)

So i know that comparisons on tuples work lexicographically:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

So from this:

>>> a = (100, 0)
>>> b = (50, 50)
>>> a > b
True

But i want to compare all elements of 2 tuples in order, so functionally i want something akin to (using values from above):

>>> a > b
(True, False) #returned tuple containing each comparison
>>> all(a > b)
False

As an example in practice, for something like screen coordinates, if you wanted to check if something was 'inside' the screen at (0,0), but done a comparison like coord > (0,0), if the x coord was bigger than 0, but the y coord was smaller it would still return true, which isn't what is needed in this case.

As sort of a sub question/discussion:
I am not sure why comparing 2 tuples of different values is returned in such a way. You are not given any sort of index, so the only thing you get from comparing a tuple (that isn't testing equality) is that at some point in the tuple, one of the comparisons will throw a true or false value when they are not equal. How could you take advantage of that?

like image 853
Joe Staines Avatar asked Apr 28 '12 00:04

Joe Staines


People also ask

Which function is use for comparing elements of both tuples?

Python tuple method cmp() compares elements of two tuples.

How do you compare two elements in a tuple in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

How do you check if elements of a tuple are same?

When it is required to check if two list of tuples are identical, the '==' operator is used. The '==' operator checks to see if two iterables are equal or not. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).


1 Answers

You can achieve this with a list comprehension and the zip built-in:

>>> a = (100, 0)
>>> b = (50, 50)
>>> [(a > b) for a, b in zip(a,b)]
[True, False]

You can use all() or any() on the returned list.

like image 140
garnertb Avatar answered Sep 30 '22 08:09

garnertb