Generate a set of common elements from two lists


This Python code uses a set comprehension to create a set named common_elements that contains the elements that are common between two lists, list1 and list2. Here's how the code works:

  • list1 = [1, 2, 3, 4, 5] and list2 = [3, 4, 5, 6, 7] : These lines initialize two lists, list1 and list2, with some integer values.
  • common_elements = {x for x in list1 if x in list2}: This line initializes the set common_elements using a set comprehension.
    • for x in list1: This part of the code sets up a loop that iterates through each element x in list1.
    • {x for x in list1 if x in list2}: For each element x in list1, this part includes x in the common_elements set if it is also found in list2.
  • print(list1): This line of code prints list1 to the console.
  • print(list2): This line of code prints list2 to the console.
  • print(common_elements): This line of code prints the common_elements set to the console.

Source Code

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = {x for x in list1 if x in list2}
print(list1)
print(list2)
print(common_elements)

Output

[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]
{3, 4, 5}

Example Programs