Python Practice › List Programs › Program 11

Common elements of two lists

EasyList Programs · 11 of 100

Write a Python program to get the common elements of two lists, in the order of the first list.

Advertisement
Input
[4, 5, 7, 9, 2, 1], [2, 5, 8, 3, 4, 7]
Output
[4, 5, 7, 2]

Approach

  1. Keep items of list1 that are in list2 (convert list2 to a set for speed).

Solution

Python
list1 = [4, 5, 7, 9, 2, 1]list2 = [2, 5, 8, 3, 4, 7]lookup = set(list2)print([x for x in list1 if x in lookup])
Output
[4, 5, 7, 2]

Line by line

Line 3

Membership checks on a set are fast, even for long lists.

Learn the concept

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

More list programs

← All 100 List Programs

Leave a Comment