Python lists have no function to detect duplicate values. The appropriate type is set.
>>>a = [1, 2, 3]
>>>b = [3, 4, 5]
>>>c = set(a + b)
>>>print(c)
{1, 2, 3, 4, 5}
>>>type(c)
<class 'set'>
>>> c = list(set(a + b))
>>>print(c)
[1, 2, 3, 4, 5]
>>>type(c)
<class 'list'>
Cannot add new duplicated values to set c, unless it is transformed into a list of list()
.
The (inefficient) way to replicate this feature for your specific case without using set()
is to iterate through the new list and not add naughty values:
a = [1, 2, 3]
b = [3, 4, 5]
c = a
for item in b:
if item not in a:
c.append(item)
print(c)
Or with list comprehension:
a = [1, 2, 3]
b = [3, 4, 5]
c = a + [item for item in b if item not in a]
print(c)
Upshot:
[1, 2, 3, 4, 5]
In the three examples the generated list is not ordered.
Thank you very much! But is there any way to do this without the set function? Because she hasn’t been seen in my classes yet.
– Guilherme Santana De Souza
Then your question falls more in the area of algorithms. I suggest opening a new question, because this one, the way it is, can still be useful to many people in the future.
– Pablo Almeida
Great then! Thank you!
– Guilherme Santana De Souza