Distinct elements from a list of mixed data types as a tuple in Python


This Python code processes a list, mixed_data, which contains a mix of different data types, and creates a tuple named distinct_mixed_elements_tuple containing the unique elements from the list. Here's how the code works:

  • mixed_data = [1, 'apple', 2.5, 'banana', 3, 'cherry']: This line initializes a variable named mixed_data and assigns it a list containing a mix of integers, floats, and strings.
  • distinct_mixed_elements_tuple = tuple(set(item for item in mixed_data)): This line initializes a variable named distinct_mixed_elements_tuple and assigns it a tuple created using a generator expression.
    • set(item for item in mixed_data): This part of the code converts the elements in mixed_data into a set, which removes any duplicate elements. It does so by iterating through each item in mixed_data.
    • tuple(...): This surrounds the set and converts it back into a tuple.
  • print(mixed_data): This line of code prints the original mixed_data list to the console.
  • print(distinct_mixed_elements_tuple): This line of code prints the distinct_mixed_elements_tuple tuple to the console.

Source Code

mixed_data = [1, 'apple', 2.5, 'banana', 3, 'cherry']
distinct_mixed_elements_tuple = tuple(set(item for item in mixed_data))
print(mixed_data)
print(distinct_mixed_elements_tuple)

Output

[1, 'apple', 2.5, 'banana', 3, 'cherry']
(1, 2.5, 3, 'apple', 'cherry', 'banana')

Example Programs