6

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.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • 3
    Will the list be arbitrarily nested? Or just flat as in your example? – Brad Solomon Oct 29 '18 at 12:58
  • 1
    What you are checking is existence of an empty tuple in the list. You can check type instead. – Sid Oct 29 '18 at 12:59
  • Why did you expect that to work? Really. I don't understand what made you think that might work. It doesn't seem to have just been a wild guess, as you seem legitimately confused about the fact it doesn't work. What was the thought process that led you to think it might do what you want? If you find yourself confused about this sort of thing, you should ask *yourself* that question and have an answer for it before posting. If you do, you'll often find that there's something you thought was true but aren't actually sure, and if you go check, then you will probably not even need to post. – jpmc26 Oct 29 '18 at 21:17

2 Answers2

28

() 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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
3

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
timgeb
  • 76,762
  • 20
  • 123
  • 145
Sid
  • 4,893
  • 14
  • 55
  • 110