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
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.
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.
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.
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
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