-2

I am trying to make a program using python that takes 2 separate lists and compares them to see the things in the list that match and output the ones that are in the first list but not in the second list. This is what i have so far (it doesn't work properly):

list1 = ("hello","goodbye","one","two","three")
list2 = ("hello","one","two")

for name in followers:
    if name == follow:
        continue
    print(name)

i want it to print the word that ARE in list1 but AREN'T in list2. can someone please help. i have been searching but haven't found the right answer so far. any help would be appreciated!

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
python
  • 5
  • 5
  • You can use `set(list1) - set(list2)`. Those are tuples, not lists by the way. – Selcuk Jan 08 '21 at 02:03
  • What are the variables `followers` and `follow`? You haven't defined those... – John Gordon Jan 08 '21 at 02:07
  • Iterate over each name in list1. If that name isn't in list2, print it. What is the difficulty? – John Gordon Jan 08 '21 at 02:08
  • This question (in this form) has received _several_ answers and was closed as a duplicate _based_ on this content. Changing it to ask an entirely new question that invalidates these answers and the close reason is _not_ an acceptable use of edits. – Henry Ecker Feb 11 '23 at 23:48

3 Answers3

5

Try using sets with the ^ operator:

list1 = ("hello","goodbye","one","two","three")
list2 = ("hello","one","two")
print(set(list1) ^ set(list2))

Or use -:

print(set(list1) - set(list2))

Both codes output:

{'goodbye', 'three'}
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

The best way to do this is to convert these lists into sets and then use difference:

print(set(list1).difference(set(list2)))
#Output: {"goodbye", "three"}
RKS2
  • 25
  • 11
0

Using set operation:

print(set(list1).difference(set(list2)))
Ashish M J
  • 642
  • 1
  • 5
  • 11