Joses Ho
Joses Ho

Reputation: 118

Differentiating a tuple from a tuple of tuples

I have a tuple, and a tuple of tuples.

import numpy as np
a = ("Control", "Group1")
b = (("Control", "Group1"), ("Control", "Group1", "Group2))

How can I tell that a is fundamentally different from b? Both

print(len(a))
print(np.shape(a))
print(len(np.shape(a)))

and

print(len(b))
print(np.shape(b))
print(len(np.shape(b)))

produce the same output:

2
(2,)
1

Thanks in advance again!

Upvotes: 2

Views: 59

Answers (2)

Jonas Schäfer
Jonas Schäfer

Reputation: 20738

You cannot, because they are not fundamentally different.

What should happen for the following?

c = (("Foo", "bar"), "baz")

It’s also a tuple, and it contains both "bare" values as well as another tuple.

If you need to detect tuples which only consist of tuples, use:

if all(isinstance(element, tuple) for element in a)

If you need to detect tuples which only consist of non-tuples, use:

if not any(isinstance(element, tuple) for element in a)

Both of the above are have a time complexity of O(n) (with n being the number of elements in a), which may not be desirable depending from where your data is coming. It is however unavoidable, unless you are willing to take the risk not actually having tuples of tuples.

Depending on what you’re doing with your data, you might actually want to check for a sequence of sequences. In that case, you should use the Sequence ABC (Python 2):

import collections.abc
if all(isinstance(element, collections.abc.Sequence) for element in a)

Upvotes: 5

TigerhawkT3
TigerhawkT3

Reputation: 49330

Use the equality operator, ==:

>>> a = ("Control", "Group1")
>>> b = (("Control", "Group1"), ("Control", "Group1", "Group2"))
>>> a == b
False

If you just want a vague idea of the general structure, and the string elements won't contain parentheses, you can count the parentheses:

>>> str(a).count('(')
1
>>> str(b).count('(')
3

Upvotes: 0

Related Questions