Skip to content
Advertisement

Unique lists within list of lists if those lists have list as one of the elements

If I have:

JavaScript

What would be the best way to get:

JavaScript

If I try:

JavaScript

I get TypeError: unhashable type: 'list'. I don’t want to remove all layers of nesting, because that would just combine everything into one list:

JavaScript

Output:

JavaScript

If two instructors have the same count (i.e. 3 in this case), then only one 3 remains because it’s a set, and I can’t group the elements of the list by every x intervals. What would be a good way to preserve that last value?

Advertisement

Answer

Given that you know which layer you want to unwrap, you could just iterate through that layer. In your particular example, it’s the second layer:

JavaScript

Note that list.extend adds multiple values to the list.

if not (inner in res): res.append(inner) gives you unique items in the top layer. Thanks to @dmitryro for the tip.

Advertisement