Finding the unique values in a list in Python can be done using the set()
function or list comprehension. Here are two examples:
Example 1:
numbers = [1, 2, 3, 2, 4, 5, 3, 1] unique_numbers = list(set(numbers)) print(f"Unique values: {unique_numbers}")
Output:
Unique values: [1, 2, 3, 4, 5]
Example 2:
fruits = ['apple', 'banana', 'orange', 'apple', 'kiwi', 'banana'] unique_fruits = [fruit for fruit in set(fruits)] print(f"Unique fruits: {unique_fruits}")
Output:
Unique fruits: [‘apple’, ‘banana’, ‘orange’, ‘kiwi’]