Reputation: 163
Could any one help me to debug the following python code?
code is shown here:
#!/usr/bin/python
# Filename: using_tuple.py
zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional
print('Number of animals in the zoo is', len(zoo))
new_zoo = ('monkey', 'camel')
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
Upvotes: 0
Views: 289
Reputation: 9
The variable new_zoo has two elements and the number of elements starts from zero
Upvotes: -1
Reputation: 3024
In this line: `print('Last animal brought from old zoo is', new_zoo[2][2])'
new_zoo[2][2] is invalid in your current code for 2 reasons: 1. Arrays are 0-indexed. new_zoo[2] refers to the 3rd element, not the 2nd. 2. Also, you will just be printing a character (specifically the 3rd character) of that zoo animal.
Upvotes: 0
Reputation: 42030
Indexing in programming languages usually starts from zero, not one. The length maybe 2, but the second element is with the index 1.
Upvotes: 2
Reputation: 23950
Where do you combine old and new zoo?
Possibilities:
>>> new_zoo = ('monkey', 'camel', zoo)
>>> new_zoo
('monkey', 'camel', ('python', 'elephant', 'penguin'))
>>> new_zoo = ('monkey', 'camel') + zoo
>>> new_zoo
('monkey', 'camel', 'python', 'elephant', 'penguin')
Upvotes: 2