Python Practice › List Programs › Program 32

Difference between two lists

EasyList Programs · 32 of 100

Write a Python program to get the items in the first list that are not in the second.

Advertisement
Input
[1, 2, 3, 4, 5], [2, 4, 6]
Output
[1, 3, 5]
[1, 3, 5, 6]

Approach

  1. Keep items of list1 not in list2.

Solution

Python
a = [1, 2, 3, 4, 5]b = [2, 4, 6]print([x for x in a if x not in b])print(sorted(set(a) ^ set(b)))
Output
[1, 3, 5]
[1, 3, 5, 6]

Line by line

Line 3

Items only in a, in their original order.

Line 4

The symmetric difference gives items in exactly one of the lists.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment