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?
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.")
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With