lo_rabb
lo_rabb

Reputation: 109

remove tuples with only one item -- python

I have a list of tuples and some of the tuples only have one item in it. How do I remove tuples with only one item from the list? I want to keep tuples with two items in it.

The tuples I have contain a string, and then an integer after it

list = ((['text'],1),(['text'],2),((3,))

Upvotes: 1

Views: 937

Answers (4)

kaycee
kaycee

Reputation: 911

You could use something like that to rebuild a new tuple with tuple that have a length greater than 1.

new_list = tuple(item for item in your_list if len(item) > 1)

Upvotes: 0

ml-moron
ml-moron

Reputation: 886

What about:

new_list = [x for x in old_list if len(x) > 1]

Upvotes: 3

fafl
fafl

Reputation: 7385

You want to create a list with squared brackets instead of parentheses, otherwise you'd create a tuple.

Also please don't call your variables like built-in names as EdChum suggested.

The solution here is to filter your list:

l=[(1,2),(3,),(4,5)]
filter(lambda x: len(x)!=1, l)

Upvotes: 2

Neo
Neo

Reputation: 3786

I may suggest:

filtered_list = [tup for tup in list if len(tup) == 2]

You can also check if tuple length is higher than one or anything else...

Upvotes: 5

Related Questions