Ambush
Ambush

Reputation: 125

understanding a tuple calculation

I'm a Python beginner and currently working with it. For the most part I understand tuples but one thing has me confused. The examples I am following, is

print 'Number of animals in the new zoo is', \
    len(new_zoo)-1+len(new_zoo[2])

I understand I have a tuple within a tuple but I don't understand why I need to use -1, I have gotten rid of the -1 and tried to specify different parameters for the first instance of new_zoo, run the script and got incorrect answers or errors.

Could someone please explain why this and if there is a better way of getting the correct answer?

Upvotes: 2

Views: 298

Answers (2)

Jorge Moreno
Jorge Moreno

Reputation: 21

First of all, backslash specified in the book is unnecessary on Python 3.4 if you have not noticed it yet. len(new_zoo) = 3 (monkey, camel and zoo are 3 items) - 1 give us 2 which is the number of animals in the new_zoo tuple. len(new_zoo[2]) = 3 because the third item in the tuple is zoo which contains 3 animals (python, elephant and penguin). The third item in the new_zoo tuple is a nested tuple hence:

len(new_zoo)-1+len(new_zoo[2]) = 2 + 3 = 5

That's why you need to subtract 1.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1123950

Whether or not to use -1 depends entirely on what the tuple models.

If the tuple contains N elements but N - 1 elements are animals and the one extra element is another tuple of animals, you don't want to count that nested tuple as an animal itself, so you subtract one.

So the tuple ('zebra', 'monkey', ('lion', 'tiger', 'puma'), 'giraffe') contains 6 animals, not 4 or 7 (the length of the outer tuple or the length of the outer tuple plus the tuple at index 2):

>>> new_zoo = ('zebra', 'monkey', ('lion', 'tiger', 'puma'), 'giraffe')
>>> len(new_zoo)
4
>>> len(new_zoo[2])
3
>>> len(new_zoo) + len(new_zoo[2])
7
>>> len(new_zoo) - 1 + len(new_zoo[2])
6

This calculation required knowing what is in the tuple, and cannot be generalised to all tuples in Python.

Upvotes: 2

Related Questions