Overview:
The slicing operation on a Python tuple creates another tuple, as specified by the two indexes within the square brackets.
The returned tuple contains the shallow copy of the elements from the original tuple.
Parameters:
Begin Index - Begin index of the tuple object
End Index - End index + 1 of the tuple object
Default values:
There are different default values assumed in the slicing operation of a tuple.
When BeginIndex is Empty: 0 is assigned as the BeginIndex
When EndIndex is Empty: len(tupleObject) is assigned as the EndIndex
When BeginIndex is Negative: The index is considered relative to the length of the tuple. The specified negative index is added to the len(tuple) to get the actual index.
Invalid Values:
-
If the BeginIndex is greater than EndIndex then the slicing operation results in an empty tuple.
-
If the index is out of bound, it results in an empty slice.
Example1: Slicing with no index speicfied
# Example Python program that returns a slice using the default |
Output:
Slicing result: ('Apple', 'Orange', 'Banana', 'Grape', 'Raspberry') |
Example2: With BeginIndex specified
# Slicing operation - 0 to the last index # Shared is a shallow copy |
Output:
Slice: ('Pen', 'Pencil', 'Notebook', 'Eraser', 'Color pen') |
Example3: With BeginIndex and EndIndex specified covering the whole tuple
# Example Python program that does slicing operation |
Output:
Slicing from 0 to 6: ('Slide', 'Swing', 'Seesaw', 'Merry-go-round', 'Jungle Gym', 'Spring Rider') |
Example4: With BeginIndex and EndIndex Specified covering a portion of the tuple
# Example Python program that creates |
Output:
Resultant slice of the tuple: ('Sunrise', 'Morning', 'Midday', 'Afternoon', 'Evening') |
Example 5: Slicing by specifying a Negative Index
# Slicing operations with negative indexes |
Output:
Favourite string instruments: ('Cello', 'Tendor viol') |