Distinct elements from multiple lists while preserving order as a tuple in Python


This Python code combines two lists, list1 and list2, into a single iterable and then creates a tuple named unique_ordered_elements_tuple containing the unique elements from both lists while preserving their order. Here's how the code works:

  • from itertools import chain: This line imports the chain function from the itertools module. The chain function is used to combine two or more iterables into a single iterable.
  • list1 = [1, 2, 3, 4, 5]: This line initializes a variable named list1 and assigns it a list containing five integers.
  • list2 = [4, 5, 6, 7, 8]: This line initializes a variable named list2 and assigns it another list containing five integers.
  • unique_ordered_elements_tuple = tuple(set(chain(list1, list2)) : This line combines list1 and list2 using the chain function. Then, it converts the combined iterable into a set, which removes any duplicate elements. Finally, it converts the set back into a tuple.
    • chain(list1, list2): The chain function takes list1 and list2 as arguments, effectively combining them into a single iterable.
    • set(...): This part converts the combined iterable into a set, removing any duplicate elements.
    • tuple(...): This surrounds the set and converts it back 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(unique_ordered_elements_tuple): This line of code prints the unique_ordered_elements_tuple tuple (which contains unique elements from both lists while preserving their order) to the console.

Source Code

from itertools import chain
 
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
unique_ordered_elements_tuple = tuple(set(chain(list1, list2)))
print(list1)
print(list2)
print(unique_ordered_elements_tuple)

Output

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

Example Programs