I'm going to compare the two lists and get only the elements that don't exist back

Asked 2 years ago, Updated 2 years ago, 154 views

I want to compare the two lists and get only the elements that are not in each other returned

For example,

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

temp3 = ["Three", "Four"] I want to work on a function that comes with it, what should I do? The code I use is too long and it's not Python, so I'd like you to tell me a better way

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

temp3 = []
for i in temp1:
    if i not in temp2:
        temp3.append(i)

list python set difference

2022-09-22 22:17

1 Answers

You can convert the list to a set to obtain a differential set.

temp3 = list(set(temp1) - set(temp2)) #ordernot preserved

#or

s = set(temp2)
temp3 = [x for x in temp1 if x not ins] #Order preserved


2022-09-22 22:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.