Write a Python Program to Print Second Last Item of a Tuple
Introduction
A tuple in Python is a collection of items stored in a single variable. We can access tuple elements using index numbers. To print the second last item, we use negative indexing.
Logic to Write the Code
- Start the program.
- Create a tuple with some elements.
- Use negative index
-2to access the second last item. - Print the element.
- End the program.
Source Code (Beginner Friendly)
# Python program to print second last item of a tuple
# Creating a tuple
items = ("apple", "banana", "cherry", "mango", "kiwi")
# Printing second last item
print("Second last item:", items[-2])
Sample Output
Second last item: mango
Viva Questions with Answers
1. What is a tuple in Python?
A tuple is a collection of elements stored in a single variable and it is immutable.
2. What does immutable mean?
Immutable means the values cannot be changed after creation.
3. What is negative indexing?
Negative indexing starts counting from the end of the tuple. Example: -1 is the last item.
4. What does items[-2] return?
It returns the second last element of the tuple.
5. Can we modify elements in a tuple?
No, tuple elements cannot be modified.
