Lecture
Accessing Specific Elements with Tuple Indexing
Like lists, tuples allow you to access the value of elements at specific positions using indexing.
The index of a tuple starts from 0, meaning the first element is at index 0.
Accessing Elements by Index
To access a specific element in a tuple, use square brackets [] with the index number.
For example, to access the third element of a tuple, use the index 2 like my_tuple[2].
Tuple Indexing Example
my_tuple = ('apple', 'banana', 'cherry') # Access the first element first_element = my_tuple[0] # Outputs apple print("first_element:", first_element) # Access the third element third_element = my_tuple[2] # Outputs cherry print("third_element:", third_element)
Negative Indexing
You can access elements from the end of a tuple using negative indices.
-1 refers to the last element, and -2 refers to the second-to-last element.
Negative Indexing Example
my_tuple = ('apple', 'banana', 'cherry') # Access the last element last_element = my_tuple[-1] # Outputs cherry print("last_element:", last_element) # Access the second-to-last element second_last = my_tuple[-2] # Outputs banana print("second_last:", second_last)
Previous lessonImmutability of Tuples and Exception HandlingNext lessonSelecting a Portion of a Tuple with Slicing
Lessons in this chapter · List and Tuple data types for storing data in sequence
- 1. How to Store Ordered Data List
- 2. How to Utilize Values in a List
- 3. List IndexError Exception Handling
- 4. How to Concatenate, Repeat, and Determine the Length of Lists
- 5. Adding Elements with append() and insert()
- 6. Multiple-choice quiz
- 7. Comparing List Concatenation and Element Addition in Python
- 8. Removing Elements with the del Keyword and pop() Function
- 9. Removing an Element with a Specific Value using remove() Function
- 10. Using the clear() Function to Remove All Values in a List
- 11. Sorting List Elements with the sort() Function
- 12. How to Check if a List Contains a Specific Element
- 13. Multiple-choice quiz
- 14. Immutable Data Type, Tuple
- 15. Immutability of Tuples and Exception Handling
- 16. Accessing Specific Elements with Tuple Indexing
- 17. Selecting a Portion of a Tuple with Slicing
- 18. How to Perform Operations on Tuples
- 19. Coding Quiz - Sorting Lists
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
Quiz
0 / 1
What is the most appropriate word for the blank?
The index of a tuple refers to the second-to-last element.
1
0
-2
-1
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help