Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

How to remove duplicate elements from a python list containing string in 1 line without…

  1. User

    How to remove duplicate elements from a python list containing string in 1 line without changing the order?

  2. Assistant

    You can use a list comprehension with an if statement checking if the element is not already in a set to remove duplicates and keep the order:

    my_list = ["hello", "world", "hello", "python", "python"]
    my_list = list(dict.fromkeys(my_list))
    
    print(my_list)
    

    Output:

    ['hello', 'world', 'python']
    
  3. User

    Okay, after that I want to remove all elements from output list that exist in another list, yet maintaining the order.

  4. Assistant

    You can simply use a list comprehension with an if statement checking if the element is not in another list to remove the unwanted elements and keep the order.

    For example, if you have a list exclude_list containing elements that you want to remove from the my_list while maintaining their order, you can do the following:

    my_list = ["hello", "world", "hello", "python", "python"]
    exclude_list = ["world", "python"]
    
    my_list = [element for element in my_list if element not in exclude_list]
    
    print(my_list)
    

    Output:

    ['hello', 'hello']
    

    Note that the order of the remaining elements is maintained as "hello" appears before "world" and "python".