0% completed
Slicing in Python allows extracting a portion of elements from a tuple while keeping the original tuple unchanged. Since tuples are immutable, slicing is the only way to create a modified version of a tuple without altering its original structure.
Tuple slicing is done using the syntax:
tuple[start:stop:step]
start
– The index where slicing begins (inclusive).stop
– The index where slicing ends (exclusive).step
– Defines how many elements to skip (default is 1
).Slicing supports both positive and negative indexing, making it flexible for working with tuples.
Positive indexing starts from 0
for the first element and increases sequentially.
full_tuple[2:7]
extracts elements from index 2
to 6
(7
is excluded).(2, 3, 4, 5, 6)
.Negative indexing starts from -1
for the last element, -2
for the second last, and so on.
full_tuple[-8:-3]
extracts elements starting from the eighth element from the end (-8
) to the third element from the end (-3
).(2, 3, 4, 5, 6)
.Negative indexing is particularly useful when working with tuples of unknown length, allowing access to elements from the end without counting from the start.
By default, slicing extracts elements in sequential order. However, the step value allows skipping elements, making slicing more flexible.
numbers[1:7:2]
starts at index 1
, stops at index 6
, and selects every second element.2
skips every alternate element.Python allows leaving out the start
or stop
values, making slicing more convenient.
numbers[:5]
extracts elements from the start up to index 5
.numbers[3:]
extracts elements from index 3
to the end.numbers[:]
creates a full copy of the tuple.These shortcuts make it easy to work with large or dynamically sized tuples.
A step value of -1
allows reversing a tuple without modifying the original.
numbers[::-1]
starts from the end and moves backward.This technique is useful for sorting operations, undo functions, and working with ordered data.
.....
.....
.....