How not to repeat values in a list in Python?

3

If I create two lists, and then I add the two, I create a third one that has all the items of the previous two:

>>>a = [1, 2, 3]
>>>b = [3, 4, 5]
>>>c = a + b
>>>print c
[1, 2, 3, 3, 4, 5]

How can I prevent 3 from being repeated in the c list? I need to create a code that takes the items from a list and adds all its values, but my list has repeated items, so it is not correct.

    
asked by anonymous 19.03.2016 / 03:03

1 answer

3

The appropriate collection to deal with elements that do not have replicates is the set . You can create a set in Python using the global function set .

>>> a  = [1, 2, 3]
>>> b = [3, 4, 5]
>>> c = set(a + b)
>>> print(c)
{1, 2, 3, 4, 5}

If you need the result to actually be a list, do list(set(a + b)) .

    
19.03.2016 / 03:12