Python slicing is a technique used to get a part of a sequence, such as a string, tuple, or list. In this technique the slice() built-in Python function is not called directly instead it is called indirectly by using the slice notation on sequences. It provides a convenient way to access elements based on their index ranges.
Slice Notation in Python.
Slicing allows Python to access and retrieve a segment of elements from a sequence, such as a string, tuple, or list. Slice notation is a concise syntax directly supported by Python for creating slices. It is used when you want to extract a part of a sequence using the colon (:) notation.
Here's a brief overview of the slice notation:
Syntax: s[start:stop:step]
- start: The starting index of the segment. The default is 0.
- stop: The index where the segment ends. It does not include the stop index itself. The default is the end of the string.
- step: The difference between each index for the segment. The default is 1. This parameter is optional and allows you to skip elements.
List Slicing in Python.
# List Slicing lst = [1, 2, 3, 4, 5] # Slicing the entire list print(lst[:]) # Slicing the first two elements print(lst[:2]) # Slicing the last two elements print(lst[-2:]) # Slicing every other element print(lst[::2])
[1, 2, 3, 4, 5]
[1, 2]
[4, 5]
[1, 3, 5]
String Slicing in Python.
# String Slicing str = "Hello, World!" # Slicing the entire string print(str[:]) # Slicing the first five characters print(str[:5]) # Slicing the last six characters print(str[-6:])
Hello, World! Hello World!
Step Slicing in Python.
# Step Slicing in Python Example string = "Hello, World!" # Slice the string from index 0 to index 5, taking a step of 2 sliced_string = string[0:5:2] print(sliced_string)
Hlo# Step Slicing with Negative Step in Python string = "Hello, World!" # Slice the string in reverse order sliced_string = string[::-1] print(sliced_string) # Output: !dlroW ,olleH
!dlroW ,olleH





