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.

1
  • Are the inner lists considered "equal" if one is a permutation of another? In both cases, what about repetitions? Commented Dec 22, 2014 at 15:53

3 Answers 3

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

Result:

True
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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".)
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.
1

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.

1 Comment

exactly what i have been looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.