Carl Burks is a software developer for a global financial institution. With over ten years experience in technology and software development for financial organizations and over twenty years of software experience, Carl Burks provides articles, musings and insight into technology issues, software development, and other selected topics.

How to remove items with only one in the collection

2016-10-18T19:59:00.002-07:00

Authors:
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:

Code


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)

Output

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