D
D
Dmitry Vasiliev2016-02-15 14:44:30
Python
Dmitry Vasiliev, 2016-02-15 14:44:30

Why aren't all elements of the list removed?

I'm trying to solve a problem on checkio. All unique elements must be removed. For some reason, when entering a list with all unique elements, such an output is obtained.

def checkio(data):
    for i in data:
        if data.count(i) < 2:
            data.remove(i)
        return data


checkio([1, 2, 3, 4, 5])            #   >>>   [2, 4]

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey K, 2016-02-15
@Veked

def checkio(data):
    return [i for i in data if data.count(i)>1]

A
Anton Fedoryan, 2016-02-15
@AnnTHony

import copy

def checkio(data):
  xdata = copy.deepcopy(data)
  for i in data:
    if (xdata.count(i) < 2):
      xdata.remove(i)
  return xdata

N
nirvimel, 2016-02-15
@nirvimel

From a performance point of view, this will be faster:

from collections import Counter

def checkio(data):
    c = Counter(data)
    return [i for i in data if c[i] > 1]

E
Evgeniy _, 2016-02-15
@GeneD88

def checkio(data):
    for i in data[-1::-1]:
        if data.count(i) < 2:
            data.remove(i)
    return data

checkio([1, 2, 3, 4, 5, ])             #   >>>   []
checkio([1, 2, 3, 4, 5, 4])             #   >>>   [4,4]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question