Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if any element in a list is in another list and return the first element found

It is easy to check if an element of a list is in another list using any():

any(elem in list2 for elem in list1)

but is there anyway to idiomatic way to return the first element found?

I'd prefer a one-line solution rather than:

for elem in list1:
   if elem in list2:
       return elem
like image 862
nluigi Avatar asked Jan 28 '16 09:01

nluigi


People also ask

How do you check if elements in a list is in another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you get the first element from each nested list of a list?

Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you check if a list contains any element of another list Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


1 Answers

Use sets: https://docs.python.org/2/library/sets.html

result = set(list1) & set(list2)

if you want to make it a conditional like any:

if (set(list1) & set(list2)):
    do something
like image 52
Serbitar Avatar answered Sep 18 '22 03:09

Serbitar