mike.pngs
mike.pngs

Reputation: 25

Compare the first item with all the items from the second list

I want to compare the first item of the list with all the items from the second list and then continue to the second item from the first list and compare it with all the the items from the second list and then the same for the third item of the first list.

Example:

first = ['one', 'two', 'three', 'four']
second = ['two' , 'one' ,'three']

'one' (from first var) compared with 'two', 'one', 'three' (from second) if it finds something equal from the second list return true.

Upvotes: 0

Views: 143

Answers (4)

Ram
Ram

Reputation: 4779

To put your exact words into code, this is how it looks.

first = ['one', 'two', 'three', 'four']
second = ['two', 'one' ,'three']

for i in first:
    for j in second:
        if i == j:
            print(f'First: {i}\tSecond: {j}')
            print(True)
First: one  Second: one
True
First: two  Second: two
True
First: three    Second: three
True

Upvotes: 0

user2390182
user2390182

Reputation: 73450

The involved contains-check is done repeatedly so it should be performed on a set (where it is O(1)):

s = set(second)

Then, you want short-circuiting for which you can use any:

match = any(x in s for x in first)  # stops on first hit

# or, collecting the matched items
matches = [x for x in first if x in s ]

You could compile these two into a one-liner, using the underlying dunder method directly:

match = any(map(set(second).__contains__, first))

Upvotes: 1

user15801675
user15801675

Reputation:

Check this. Use 2 forloops

def compare(first,second):
    return [x==y for x in first for y in second] #====Return a list of True or False

Or

def compare(first,second):
    return any(x==y for x in first for y in second) #====Returns True or False

Upvotes: 0

Joshua Fox
Joshua Fox

Reputation: 19655

An idiomatic way to do this is with sets.

first = ['one', 'two', 'three', 'four']
second = ['two', 'one', 'three']
result = bool(set(first) & set(second))
print(result)

Upvotes: 0

Related Questions