Skip to content
Advertisement

How do I print the overlap value from two lists by trimming the first 3 letters using Python 3

My goal is using Python 3 to check if there are any top 3 letters that overlap between List_A and List_B, and print the overlap data from List_B.

List_A = ["apple123","banana3","345banana","cat123","apple456"]
List_B = ["apple123","345123","dog234","apple4","cat002345"]

The following is the for loop of printing the overlap data between List_A and List_B.

for i in List_A:
    if i in List_B: 
        print(i)

The output is

apple123

Next, I try to select the first 3 letters and append them in the new List of A and B, then compare if there is any overlap.

List_A1 = []
for i in List_A:
    List_A1.append(i[0:3])

List_B1 = []
for i in List_B:
    List_B1.append(i[0:3])

# check if any top 3 letters overlap
for i in List_A1:
    if i in List_B1: print(i)

the output is

app
345
cat
app

However, my expected output is the original data in List_B, such as:

apple123    
345123
apple4
cat002345

May I ask how could I modify the code?

Advertisement

Answer

The code was printing the elements in 3-letters list. You might first get its index and print the overlapped with same index in original list.

# for i in List_A1:               # changes from here...
for i in range(len(List_A1)):   # per each index i in List_A1
    if List_A1[i] in List_B1:   # element i overlapped in List_B1
        print(List_A[i])        # print the item in List_A by same index
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement