What is Slices in python

12/17/2021

#What is slices #python #Python

Go Back

Understanding Slices in Python

Slices in Python allow you to extract a subset of elements from sequences like lists, tuples, and strings. They provide an easy and efficient way to manipulate and access data.

What Are Slices?

Slices are objects that can be stored in variables and used to extract parts of sequences. We use integers to specify the upper and lower bounds of a slice or utilize 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])    # Output: ['b', 5, 11]
print(text[s])   # Output: 'aSc'
print(tpl[s])    # Output: (4, 5, 6)

Slicing a List with Negative Indices

Python allows negative indices, which count from the end of the sequence.

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 using negative step
print(numbers[::-1])   # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Slicing a List with Step

A step value determines the interval between elements in the slice.

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 allow counting from the end of the sequence.

Slicing in Python is a powerful tool for data manipulation, making code more concise and readable.

#What is slices #python #Python

Table of content