Python - Function to intersect Sequences

Introduction

The following code creates a function to make a general intersection utility:

Demo

#for every item in the first argument, 
#if that item is also in the second argument, 
#append the item to the result. 
# ww w .ja va2 s. c  o  m
def intersect(seq1, seq2): 
    res = []                     # Start empty 
    for x in seq1:               # Scan seq1 
        if x in seq2:            # Common item? 
            res.append(x)        # Add to end 
    return res 

s1 = "TEST" 
s2 = "SCAM" 
i= intersect(s1, s2)            # Strings 
print( i )

Result

Here, we've passed in two strings, and we get back a list containing the characters in common.

The function could be replaced with a single list comprehension expression:

l= [x for x in s1 if x in s2] 
print( l )

Related Topic