How to get unique values from a list in Python

Published on Aug. 22, 2023, 12:16 p.m.

To get unique string values from a list in Python, you can use a set to remove duplicates. Here’s an example:

my_list = ['hello', 'world', 'hello', 'python', 'world']
unique_strings = set(my_list)
print(unique_strings)  # Output: {'python', 'world', 'hello'}

In this example, we first define a list my_list containing a mix of string elements, including some duplicates. We then use the set() function to remove duplicates and create a new set unique_strings containing only the unique string elements. Finally, we print the resulting set unique_strings, which contains only the unique string elements from the original list.

Note that using a set to remove duplicates will change the order of the original list. If you need to maintain the original order of the list, you can use a for loop and an if statement to check if each element is already in a new list. Here’s an example:

my_list = ['hello', 'world', 'hello', 'python', 'world']
unique_strings = []
for element in my_list:
    if element not in unique_strings and type(element) == str:
        unique_strings.append(element)
print(unique_strings)  # Output: ['hello', 'world', 'python']

Here, we first define an empty list unique_strings that will store only the unique string elements. We use a for loop to iterate over the elements of the original list. On each iteration, we check if the current element is not already in the unique_strings list (to remove duplicates) and if it is a string using an if statement. If it meets both conditions, we append it to the unique_strings list using the append() method. Finally, we print the resulting unique_strings list, which contains only the unique string elements from the original list in their original order.

Tags:

related content