-1
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
if x == y:
    print("Numbers found")
else:
    print("Numbers not found")

I want to print the numbers which are not present in list y.

  • Does this answer your question? [Python find elements in one list that are not in the other](https://stackoverflow.com/questions/41125909/python-find-elements-in-one-list-that-are-not-in-the-other) – Tomerikoo Jan 22 '22 at 23:26

5 Answers5

3

The fastest way is to transform both in sets and print the difference:

>>> print(set(x).difference(set(y)))
{6}

This code print numbers present in x but not in y

Joao Donasolo
  • 359
  • 1
  • 9
1
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]

for i in x:
    if i in y:
        print(f"{i} found")
    else:
        print(f"{i} not found")
Robin Sage
  • 969
  • 1
  • 8
  • 24
1

You can do like this:

x = [1,2,3,4,5,6]
y = [1,2,3,4,5]

for i in x:
    if i not in y:
        print(i)
Arnav
  • 163
  • 1
  • 8
1

to get not matches:

def returnNotMatches(a, b):
    return [[x for x in a if x not in b], [x for x in b if x not in a]]

or

new_list = list(set(list1).difference(list2))

to get the intersection:

list1 =[1,2,3,4,5,6]
list2 = [1,2,3,4,5]
list1_as_set = set(list1)
intersection = list1_as_set.intersection(list2)

output:

{1, 2, 3, 4, 5}

you can also transfer it to a list:

intersection_as_list = list(intersection)

or:

new_list = list(set(list1).intersection(list2))
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
1

This is the best option in my opinion.

x =[1,2,3,4,5,6]
y = [1,2,3,4,5]

for number in x:
    if number not in y:
        print(f"{number} not found")
Key27
  • 9
  • 2