-2

I have a list containing the strings

a=['boy', 'girl', 'man', 'boy']

Now I want a new list that doesn't have repeated elements

b = ['boy', 'girl', 'man']

How do I do that in Python?

mrbright
  • 49
  • 5
  • 1
    Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys. like list(dict.fromkeys(a)) where a = ['boy', 'girl', 'man', 'boy'] – Haseeb Aug 22 '21 at 11:33

2 Answers2

1

from DOC of set:

|Sets are mutable unordered collections of unique elements.

use set like below:

a=['boy', 'girl', 'man', 'boy']

list(set(a))

output:

['man', 'boy', 'girl']

by thanks of @jonrsharpe for maintaining of list's order you can try this:

from collections import OrderedDict
a=['boy', 'girl', 'man', 'boy']
list(OrderedDict.fromkeys(a))

output:

['boy', 'girl', 'man']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
-1
# import libraries
import numpy as np
  
a=['boy', 'girl', 'man', 'boy']
b = ['boy', 'girl', 'man']

print("Union of two arrays :", np.union1d(a, b))