How to remove items with only one in the collection

2016-10-19 02:59:00 +0000 - Written by Carl Burks

Someone recently asked me this question: How can I go through a set of data and remove items with only one in the set?

I responded by asking him which language. He didn't have a preference. I told him to look up the SQL "having" statement.

That would have been that, but he wasn't familiar with SQL. He would have had to install a SQL instance. With docker, installing would be a trival task. The familiarity would have been the bottleneck. Being the kind-hearted coder I am, I suggested he read up on list comprehensions in Python, the language I believe he has the most familiarity with.

Since I've got a blog, and I haven't posted in a I while, I took this chance to go ahead and post a solution:


def remove_items_with_only_one(data):
    return [_ for _ in data if len(_) > 1]

sampleData = [[1,1,2,3,4,5,6],[123,2,23,4,23,12,1],[12,4,5,5,6,2,123],[1],[24]]
print remove_items_with_only_one(sampleData)


[[1, 1, 2, 3, 4, 5, 6], [123, 2, 23, 4, 23, 12, 1], [12, 4, 5, 5, 6, 2, 123]]