What is slicing in Python?

0
0

In Python, slicing is a technique for accessing a portion of a sequence (such as a list, tuple, or string) by specifying a range of indices. The syntax for slicing is sequence[start:stop:step], where start is the index of the first element to include in the slice (inclusive), stop is the index of the last element to include in the slice (exclusive), and step is the step size between elements (default is 1).

Here are some examples of slicing:

# Slicing a list
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # [2, 3, 4]
print(my_list[2:]) # [3, 4, 5]
print(my_list[:3]) # [1, 2, 3]
print(my_list[::2]) # [1, 3, 5]
print(my_list[::-1]) # [5, 4, 3, 2, 1]

# Slicing a string
my_string = “hello world”
print(my_string[2:7]) # “llo w”
print(my_string[6:]) # “world”
print(my_string[:5]) # “hello”
print(my_string[::2]) # “hlowrd”
print(my_string[::-1]) # “dlrow olleh”

 

As you can see, slicing allows you to extract a portion of a sequence based on the indices specified. You can also use slicing to reverse a sequence by using a negative step size.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.