Go Back

What is Slices in python

12/17/2021
All Articles

#What is slices #python #Python

What is Slices in python

What is Slices? 

Slices are objects so they can be stored in variables. Some data structures allow for indexing and slicing such as lists, strings, and tuples.

We can use integers to specify the upper and lower bound of the slice or use a slice object.
 

Example :

s = slice(3,6)

lst = [1, 3, 'a', 'b', 5, 11, 16]

text = 'DataScience'

tpl = (1,2,3,4,5,6,7)

print(lst[s])

['b', 5, 11]

print(text[s])

aSc

print(tpl[s])

(4, 5, 6)

Example

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice from -5 to -2 (from the end)
print(numbers[-5:-2])  # Output: [5, 6, 7]

# Reverse the list with negative step
print(numbers[::-1])  # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Example :

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Slice with step

sliced_numbers_step = numbers[1:8:2]

print(sliced_numbers_step) # Output: [1, 3, 5, 7] # Slice with negative step (reversing)

reversed_numbers = numbers[::-1]

print(reversed_numbers) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
 

Conclusion

Slicing: Extracts a subset of elements from a sequence.
Syntax: sequence[start:stop:step].
Defaults:
start defaults to 0.
stop defaults to the length of the sequence.
step defaults to 1.
Negative Indices: Count from the end of the sequence.
Slicing in Python is a powerful feature that allows you to easily manipulate and access portions of sequences with concise and readable code.

Article