How not to repeat values in a Python list?

Asked

Viewed 1,779 times

6

If I create two lists, and then add the two, I create a third that owns 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 do I make the 3 is not repeated in the list c? I need to create a code that takes items from a list and adds all their values, but my list has repeated items, and so is not correct.

3 answers

5


The appropriate collection to deal with elements that have no repetitions is the ensemble. You can create a Python set 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 really need the result to be a list, do it list(set(a + b)).

  • 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.

  • 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.

  • 1

    Great then! Thank you!

1

If you need to keep order, access list indexes and you are dealing with lists in your project, you are not required to use set(). There is a simple solution using dict.fromkeys() to remove the repetitions:

>>> a = [1, 2, 3]
>>> b = [3, 4, 5]
>>> c = a + b
>>> mylist = list(dict.fromkeys(c))
>>> print(mylist)
[1, 2, 3, 4, 5]

0

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.