Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there's a tuple inside a list?

Tags:

python

Why does this:

seq = [(1, 2), (3, 4), (5, 6)]
print(() in seq)

return False? How can I check if there's a tuple, or even a generic sequence, inside a sequence with no specific values, as in this answer.

like image 265
Ericson Willians Avatar asked Oct 29 '18 12:10

Ericson Willians


2 Answers

() is an empty tuple. seq does not contain an empty tuple.

You want

>>> seq = [(1, 2), (3, 4), (5, 6)]
>>> any(isinstance(x, tuple) for x in seq)
True

For a generic sequence you can use

>>> from collections import abc
>>> any(isinstance(x, abc.Sequence) for x in seq)
True

However, lots of objects are informally treated as sequences but neither implement the full protocol abc.Sequence defines nor register as a virtual subclass of Sequence.

Read this excellent answer for additional information.

You can find a question about detecting sequences here.

like image 71
timgeb Avatar answered Oct 02 '22 01:10

timgeb


What you are checking is the existence of an empty tuple in the list.

You can check the type instead.

def has_tuple(seq):    
    for i in seq:
        if isinstance(i, tuple):
            return True
    return False
like image 35
Sid Avatar answered Oct 01 '22 23:10

Sid