Home > OS >  How to make two different list of strings same?
How to make two different list of strings same?

Time:12-01

I have two random lists of strings. The length of two lists won't be necessarily equal all the time. There is no repetition of the elements within a list.

list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']

I want to compare the two lists, and the final output should be two lists with all common elements.

Expected output:

list1_final=['A', 'A-B', 'B', 'C','D']
list2_final=['A', 'A-B', 'B','C', 'D']

How can I achieve this with a minimum number of lines of code?

CodePudding user response:

Use the set python module. Just using set1.intersection(set2) you can have the common elements between set1 and set2

CodePudding user response:

Youve requested 2 lists with all common elements:

list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']

list1_final=[]
list2_final=[]

for item in list1:
    if item in list2:
        list1_final.append(item)
        list2_final.append(item)

returns

list 1 = ['A', 'A-B', 'B'] list 2 = ['A', 'A-B', 'B']

Now your output doesnt match the question asked, do you want all items in both lists? not just the common ones?

  • Related