Tuple of common elements between two lists in Python


This Python code creates a tuple called common, which contains the elements that are common between list1 and list2. Here's how the code works:

  • list1 = [1, 2, 3, 4, 5]: This line initializes a variable named list1 and assigns it a list containing five numbers.
  • list2 = [4, 5, 6, 7, 8]: This line initializes a variable named list2 and assigns it a list containing five numbers.
  • common = tuple(x for x in list1 if x in list2): This line of code initializes a variable named common and assigns it a tuple created using a generator expression.
    • for x in list1: This part of the code sets up a loop that iterates through each element x in list1.
    • if x in list2: For each element in list1, it checks if the element is also present in list2 by evaluating x in list2.
    • x: If an element is found in both list1 and list2, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated common elements into a tuple.
  • print(list1): This line of code prints the original list1 to the console.
  • print(list2): This line of code prints the original list2 to the console.
  • print(common): This line of code prints the common tuple (which contains the common elements between list1 and list2) to the console.

Source Code

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = tuple(x for x in list1 if x in list2)
print(list1)
print(list2)
print(common)

Output

[1, 2, 3, 4, 5]
[4, 5, 6, 7, 8]
(4, 5)

Example Programs