Reputation: 413
Is there an easy way to see if a list of tuples in python are the same (same tuple in each position, where a tuple is the same if their corresponding elements are the the same)? I know how to manually loop through the list and compare each element, but was wondering if there were any library functions that could do this?
Upvotes: 4
Views: 2274
Reputation: 991
In python 3.x
, you can check if two lists of tuples
a
and b
thus:
import operator
a = [(1,2),(3,4)]
b = [(3,4),(1,2)]
# convert both lists to sets before calling the eq function
print(operator.eq(set(a),set(b))) #True
Upvotes: 0
Reputation: 1886
You can use cmp() compares elements of two lists.
list1 = [('a', 1), ('b', 1)]
list2 = [('a', 1), ('b', 1)]
print cmp(list1, list2)
If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned.
Upvotes: 4
Reputation: 308206
len(list1) == len(list2) and all(a == b for a,b in zip(list1, list2))
That was my first guess, but I just tried the obvious and simple solution and that worked too:
list1 == list2
Upvotes: 2