Ritik Samaiya
Ritik Samaiya

Reputation: 155

Comparison of elements within a same list in list of lists

This might sound easy but I am unable to give a proper approach for this. I want to Delete a whole list from a list of lists that carries two equal elements.
EX

[[5,5,5],[5,10,5],[5,10,15],[5,10,10],[5,10,20]]

Out

[[5,10,15],[5,10,20]]

NOTE- The sublist's size is fixed, that is == 3.

Upvotes: 0

Views: 135

Answers (2)

Sushant
Sushant

Reputation: 3669

Can be done by list comprehension, like so -

[i for i in my_list if len(set(i)) == len(i)]

What we are doing here is we are checking how many unique elements are the in a list of list, by using set(i), if after set, it still contains 3 elements, that means all the elements are unique and we need that list.

If we look at the code and the list -

my_list = [[5,5,5],[5,10,5],[5,10,15],[5,10,10],[5,10,20]]
# [i for i in my_list] will get us [5,5,5], [5,10,5] ...
# applying set(i) on, for example first i will give us set([5])
# and len(set([5])) is not equal to len(i)
# therefore O/P will be
O/P = [i for i in my_list if len(set(i)) == len(i)]
#[[5, 10, 15], [5, 10, 20]]

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71451

You can compare the length of an element as a set to the length of the original list:

d = [[5,5,5],[5,10,5],[5,10,15],[5,10,10],[5,10,20]]
new_d = [i for i in d if len(set(i)) == len(i)]

Output:

[[5, 10, 15], [5, 10, 20]]

Upvotes: 4

Related Questions