Absolute Zero
Absolute Zero

Reputation: 3

Finding the first occurrence in 2 lists in Python

I'm having trouble doing this, I want to do a function that does this : I have 2 lists : list1 = [8,6,0] and list2 = [6,0]. I want to keep the first value that's the same between the 2 lists (6 here). Like if I had list1 = [a,b,c] and list2 = [b,c]. I'd like to keep only value b. I've already tried this :

def listFirstValue (list1,list2) :
for x in list1 :  
  for y in list2 :
    if x == y :
      break
  break
return a

Thank you for your response.

Upvotes: 0

Views: 1522

Answers (2)

a_guest
a_guest

Reputation: 36249

If the items in list2 are hashable it might be good to create a corresponding set first, for faster lookups (set has O(1) membership test):

lookup = set(list2)
next(x for x in list1 if x in lookup)

Upvotes: 0

yatu
yatu

Reputation: 88236

I'd do this with a generator comprehension using next to retrieve the first element in list1 that is contained in list2:

list1 = [8,6,0] 
list2 = set([6,0])

next(i for i in list1 if i in list2)
# 6

A little safer, avoids errors in the case where no elements are contained in list1:

next((i for i in list1 if i in list2), None)

Upvotes: 4

Related Questions