Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements that occur in some but not all lists

Tags:

python

Suppose I have several lists of integers like so:

[0,3,4]
[2,3,4,7]
[2,3,4,6]

What's the most efficient / most pythonic way to build a single list of all elements that occur in at least one list but do not occur in all lists? In this case it would be

[0,2,7,6]
like image 640
Ben S. Avatar asked Feb 10 '16 20:02

Ben S.


People also ask

How do you find the elements of a list that are not in another list?

To find the elements in one list that are not in the other: Use the set() class to convert the first list to a set object. Use the difference() method to get the elements in the set that are not in the list. Use the list() class to convert the set object to a list.

How do you check whether an element is present in the list or not?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you find a certain value in a list Python?

Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List. Another way to find the indices of all the occurrences of a particular item is to use list comprehension. List comprehension is a way to create a new list based on an existing list.

How do you find all the elements in the list is same in Python?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.


1 Answers

The answer is implied in your question .. if you substitute "set" for "lists". As StephenTG posted, simply get the difference between the union and the intersection of all lists.

The advantage of using sets over Counter is that you need make no assumptions about values appearing only once in each list.

The following works regardless of how many lists you have:

> list_of_sets = [set(l) for l in lists]
> set.union(*list_of_sets) - set.intersection(*list_of_sets)
{0, 2, 6, 7}
like image 51
kdopen Avatar answered Sep 18 '22 17:09

kdopen