Remove Repeated Integers List in Python

Asked

Viewed 2,091 times

0

I would like to remove repeated integers from a list and return a new list.

lista = [1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 8]

The result would have to be this:

[1, 2, 3, 4, 5, 6, 7, 8]
  • Take a look at the set https://answall.com/questions/77699/para-que-serve-o-set-no-python

  • 2

    Possible duplicate of What’s the set for in Python?

  • But the set updates a list, I would like an algorithm or some native Python lib that removes items from the duplicate list.

  • What’s wrong with using the set, @Guilhermeia?

  • I hadn’t understood exactly what the set, really is a duplicate. Thanks @LINQ and @Leonardo Pessoa

  • You can take a look at this Link.

Show 1 more comment

2 answers

6


The set does just that. If you make a point that the type of the result is a list, just do the conversion of set for such

a = [1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 8] 
b = set(a) # Conjunto a partir de 'a', vai remover todos os repetidos

c = list(b) # lista a partir de 'b', vai converter o set numa list

print(a) # [1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 8]
print(b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(c) # [1, 2, 3, 4, 5, 6, 7, 8]
  • There is only one error in the 4 line, the parameter of the list is the b and not c. Thank you

0

If you just want to remove the repeated integers from the cited list, you can use the following algorithm...

lista = [1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 8]

nova_lista = list()
for c in lista:
    if c not in nova_lista:
        nova_lista.append(c)

print(nova_lista)

Note that in this algorithm the for travels lista and, if each value of c not exist in nova_lista, adds it in nova_lista. And otherwise you don’t add it.

At the end we will have the nova_lista formed by all the elements of lista without the repeated values.

Now, if it is necessary to generalize the logic of this algorithm to treat cases where we will have varied lists, we can use the following algorithm...

lista = sorted(list(map(int, input('Digite todos os valores da lista: ').split())))

nova_lista = list()
for c in lista:
    if c not in nova_lista:
        nova_lista.append(c)

print(nova_lista)

When we executed this second algorithm we received the following message: Digite todos os valores da lista:. Right now we must type all the values of the list in the same line, separated for a single space and press enter.

At that point the algorithm will capture all the entered values, convert them to inteiros and store them, in an orderly manner, in lista. Then the for will travel lista and, if each value of c not exist in nova_lista, adds it in nova_lista. And otherwise you don’t add it.

If the future lists used in this second algorithm contain elements of real value, just change the data type of int for float.

Browser other questions tagged

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