Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if an element of a list is in another list?

Tags:

I want to know if at least one element in a first list can be found in a second list.

I can see two ways to do it. Let's say our lists are:

List<string> list1 = new[] { "A", "C", "F", "H", "I" }; List<string> list2 = new[] { "B", "D", "F", "G", "I" }; 

The first approach uses a loop:

bool isFound = false; foreach (item1 in list1) {     if (list2.Contains(item1))     {         isFound = true;         break;     } } 

The second one uses Linq directly:

bool isFound = list1.Intersect(list2).Any(); 

The first one is long to write and not very straightforward/easy-to-read. The second one is short and clear, but performances will be low, especially on large lists.

What may be an elegant way to do it?

like image 474
Arseni Mourzenko Avatar asked Feb 20 '11 22:02

Arseni Mourzenko


People also ask

How do you check if an element in one list is present in another list?

Using any() along with a generator expression: list1 = ['item1','item2','item3'] list2 = ['item4','item5','item3'] if any(x in list1 for x in list2): print("Duplicates found.") else: print("No duplicates found.")

How do you see if an item in a list is in another list Python?

To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.

How do you check a list is a subset of another list?

USE set. issubset() TO CHECK IF A LIST IS A SUBSET OF ANOTHER LIST Use set(list) to convert the lists to sets. Call set1. issubset(set2) to return a Boolean indicating whether set1 is a subset of set2.


1 Answers

The second one has better performance on large lists than the first one. Intersect puts the elements of one list into a hash table before checking the other list's elements for membership.

like image 124
mqp Avatar answered Oct 04 '22 23:10

mqp