Lecture
Selecting a Portion of a Tuple with Slicing
Just like lists, tuples allow you to extract consecutive elements using slicing.
To slice a tuple, use square brackets ([]) with the start index and end index separated by a colon (:), written as [start_index:end_index].
The start index is included in the extraction, whereas the end index is not.
Let's look at an example.
Tuple Slicing Example
my_tuple = (1, 2, 3, 4, 5, 6) # Slicing from the 2nd to the 4th element slice_tuple = my_tuple[1:4] # Excludes the 5th element, my_tuple[4] # Outputs: (2, 3, 4) print(slice_tuple)
my_tuple[1:4] slices from the second element (index 1) to the fourth element (index 3).
The fifth element of my_tuple, my_tuple(4), is not included in the extraction through slicing.
Omitting Start or End Index
Omitting the start index begins the slice at the first element.
Omitting the end index slices the tuple up to the last element.
Omitting Start or End Index in Tuple Slicing Example
my_tuple = (1, 2, 3, 4, 5, 6) # From the beginning to the third element, my_tuple[2] beginning_slice = my_tuple[:3] # Outputs: (1, 2, 3) print(beginning_slice) # From the fourth element, my_tuple[3], to the end end_slice = my_tuple[3:] # Outputs: (4, 5, 6) print(end_slice)
Using Negative Indices
With negative indices, you can start slicing from the end of the tuple.
Tuple Slicing with Negative Indices Example
# Slicing from the third-to-last element to the end negative_slice = my_tuple[-3:] # Outputs: (4, 5, 6) print(negative_slice)
Previous lessonAccessing Specific Elements with Tuple IndexingNext lessonHow to Perform Operations on Tuples
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
When slicing a tuple like [start_index:end_index], the end index is not included in the sliced result.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help