5

Say I have two lists of lists in Python,

l1 = [['a',1], ['b',2], ['c',3]]
l2 = [['b',2], ['c',3], ['a',1]]

What is the most elegant way to test they are equal in the sense that the elements of l1 are simply some permutation of the elements in l2?

Note to do this for ordinary lists see here, however this uses set which does not work for lists of lists.

Community
  • 1
  • 1
rwolst
  • 12,904
  • 16
  • 54
  • 75
  • Are the inner lists considered "equal" if one is a permutation of another? In both cases, what about repetitions? – Kyle Strand Dec 22 '14 at 15:53

3 Answers3

16
l1 = [['a',1], ['b',2], ['c',3]]
l2 = [['b',2], ['c',3], ['a',1]]
print sorted(l1) == sorted(l2)

Result:

True
Kevin
  • 74,910
  • 12
  • 133
  • 166
3

Set doesn't work for list of lists but it works for list of tuples. Sou you can map each sublist to tuple and use set as:

>>> l1 = [['a',1], ['b',2], ['c',3]]
>>> l2 = [['b',2], ['c',3], ['a',1]]
>>> print set(map(tuple,l1)) == set(map(tuple,l2))
True
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
  • 2
    This would lose information about the count: in other words, if `l1` had 10 `['a', 1]` sublists and `l2` only had 1, it would still say they're equal. (Maybe that's what the OP wants, but it's not what I'd guessed based on "permutation".) – DSM Dec 22 '14 at 15:58
  • It might not be what OP wanted but this is what I actually needed searching with this question as in my case I did not have repetions and the lists inside weren't ordered. – Òscar Raya May 21 '23 at 21:40
0

For one liner solution to the above question, refer to my answer in this question

I am quoting the same answer over here. This will work regardless of whether your input is a simple list or a nested one.

let the two lists be list1 and list2, and your requirement is to ensure whether two lists have the same elements, then as per me, following will be the best approach :-

if ((len(list1) == len(list2)) and
   (all(i in list2 for i in list1))):
    print 'True'
else:
    print 'False'

The above piece of code will work per your need i.e. whether all the elements of list1 are in list2 and vice-verse. Elements in both the lists need not to be in the same order.

But if you want to just check whether all elements of list1 are present in list2 or not, then you need to use the below code piece only :-

if all(i in list2 for i in list1):
    print 'True'
else:
    print 'False'

The difference is, the later will print True, if list2 contains some extra elements along with all the elements of list1. In simple words, it will ensure that all the elements of list1 should be present in list2, regardless of whether list2 has some extra elements or not.

Community
  • 1
  • 1
Pabitra Pati
  • 457
  • 4
  • 12