top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python Slicing

Introduction

Python's slicing capabilities are essential and necessary for data processing and manipulation because they make it simpler to work concisely and effectively with data sequences. This tutorial will go in-depth on how to use the Python slice function, dissecting its syntax, parameters, and use cases. This tutorial aims to offer a complete guide to Python’s slicing functionalities.

Overview

Slicing is a fundamental and potent Python feature that makes it simple to work with subsequences and facilitates data manipulation and analysis. It works with strings, tuples, and other iterable types in addition to lists. The Python slice function, a crucial tool for text editing and data translation, serves as the tutorial's focal point.

What is an Index?

An index in Python slicing is a numeric position that designates a certain element's location inside a sequence (such as a string, list, or tuple). The unique index for each element in a series starts at 0 for the first element, 1 for the second element, and so on.

Important details regarding indexes in Python slicing:

  • Zero-Based Indexing: Due to Python's usage of zero-based indexing, the first element in a series has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.

  • Positive and Negative Indexing: If you want to access elements from the beginning of the series, you can use positive indexes (beginning with 0), and if you want to access elements from the end of the sequence, you can use negative indexes (beginning with -1 for the final element, -2 for the next-to-last element, and so on).

For example, my_list[0] will access the first element, my_list[-1] will access the last element, and my_list[-2] will access the second last element.

  • Index Range: You specify a range of indexes when using slicing to extract a section of the sequence. The element at the starting index is inclusive (i.e., it is part of the slice) while the element at the terminating index is exclusive (i.e., it is not part of the slice).

For instance, my_list[2:5] extracts the items at positions 2, 3, and 4, but not the element at position 5.

What is Python Slicing?

The process of extracting and manipulating components within sequences like lists, strings, and tuples is made simpler by the powerful feature called "slicing" which is available in the flexible and popular programming language Python. Slicing is a fundamental Python programming idea, and in this introduction, especially for those unfamiliar with Python, we'll examine what it is and how it might be applied.

A sequence can be thought of as a collection of things that are in a specific order, such as a string of letters, a list of numbers, or a tuple of values. You can access particular sections of these sequences using Python's slicing feature instead of having to loop through each element one at a time.

Python Slicing Syntax

By defining a range of indices, slicing in Python can be used to extract a piece of a sequence (such as a text, list, or tuple). Slicing's basic syntax is as follows:

sequence[start:stop:step]

The meaning of each component of the slicing syntax is explained below:

  • sequence: You want to perform the slice function on this sequence. This could be a text, list, or tup

  • start: is the index of the slice's first element that you want to include. Since it is inclusive, the element at this index will be included in the final product. It defaults to 0 (the start of the series) if absent.

  • stop: is the index of the primary element that you want to omit from the slice. The element at this index won't be included in the outcome since this index is exclusive. It defaults to the sequence's length (the end of the sequence) if it is absent.

  • step: the distance or step size between slice parts. If left blank, it defaults to 1 and includes all elements between start and stop. To make the pieces appear out of sequence, use a negative step.

Python Slicing using Negative Numbers

By counting positions from the end of a sequence and using negative values as indices, cutting with negative indices in Python enables you to remove elements from sequences (such as strings, lists, or tuples). When you need to deal with pieces from the sequence's end but are unsure of their exact length, this capability comes in helpful.

Here are some instances of negative index slicing:

Code:

my_list = [0, 1, 2, 3, 4, 5]
# Accessing elements from the end of the list
last_element_of_the_list = my_list[-1]  # 5
second_last_element_of_the_list = my_list[-2]  # 4
# Slicing a portion of the list using negative indices
subset = my_list[-3:-1]  # [3, 4] (from the third-to-last to the second-to-last element)

In the aforementioned example, my_list[-1] accesses the very last element of the list, followed by my_list[-2] and my_list[-3]. Remember that the starting index is inclusive and the stopping index is exclusive when slicing with negative indices.

When you don't know how long a sequence is but still need to work with pieces near the conclusion, negative indices are especially helpful. 

Code:

my_list = [0, 1, 2, 3, 4, 5]
# Slice to get the last three elements
last_three_of_the_list = my_list[-3:]  # [3, 4, 5]
# Reverse the list using negative indices
reversed_list = my_list[::-1]  # [5, 4, 3, 2, 1, 0]

When working with sequences, especially when you need to work with components at both ends of the series, slicing with negative indices can make your code more flexible and legible.

Specify Step of the Slicing

You can extract elements from a sequence (such as a string, list, or tuple) with a given gap between them by using the advanced capability of specifying the step in slicing. How many places are skipped between each slice element depends on the step value. You use the start:stop:step format to include the step value in the slicing syntax.

To better understand how specifying the step functions, let's look at some examples:

Code:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slicing with a step of 2 (every second element)
subset = my_list[0::2]
print(subset)
# Result: [0, 2, 4, 6, 8]
# This slice starts from index 0, goes to the end, and selects every second element.
# Slicing with a step of 3 (every third element)
subset = my_list[1::3]
print(subset)
# Result: [1, 4, 7]
# This slice starts from index 1, goes to the end, and selects every third element.
# Slicing with a negative step to reverse the list
reversed_list = my_list[::-1]
print(reversed_list)
# Result: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# This slice starts from the end, goes to the beginning, and selects every element with a step of -1.
# Combining start, stop, and step to extract a specific pattern
subset = my_list[2:8:2]
print(subset)
# Result: [2, 4, 6]
# This slice starts from index 2, goes up to index 8 (exclusive), and selects every second element.

By defining the step, you can quickly remove parts from a series at predetermined intervals, skip undesirable elements, or even reverse the order. This function is very helpful for extracting periodic data points from a bigger dataset or filtering data.

Reversing elements of different Data Structures

Slicing can be used in Python to reverse the elements of a data structure, such as a list or string. By slicing, you can reorder the elements in a series to produce a new one. The following describes how to reverse items in several data structure types:

Reversing a List

Code:

our_list = [1, 2, 3, 4, 5]
reversed_list = our_list[::-1]
print(reversed_list)
# Output: [5, 4, 3, 2, 1]
In this case, our_list[::-1] makes a new list with the components of my_list arranged in the opposite direction.

Reversing a String

Code:

our_string = "Hello, let us learn Python!"
reversed_string = our_string[::-1]
print(reversed_string)
# Output: "!nohtyP nrael su tel ,olleH"
Slicing can also be used to reverse the characters in strings.

Reversing a Tuple

Because tuples cannot be changed, you must first convert them into another data structure, such as a list, reverse them, and then, if necessary, convert them back into tuples:

Code:

our_tuple = (1, 2, 3, 4, 5, 6)
reversed_list = list(our_tuple)[::-1]
reversed_tuple = tuple(reversed_list)
print(reversed_tuple)
# Output: (6, 5, 4, 3, 2, 1)

slice() function Syntax in Python

When a slice object is created in Python using the slice() function, it can be used to extract a section of a sequence (such as a string, list, or tuple) using the slice notation. Start, Stop, and Step are the three optional inputs that the slice() function accepts. These arguments are equivalent to the sequence[start:stop:step] parameters used in slicing notation.

The slice() function's syntax is as follows:

slice(start, stop, step)

The slice() function can be used as shown in the following examples:

Code:

our_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a slice object to represent a slice from index 2 to 5 (exclusive)
our_slice = slice(2, 5)
subset = our_list[our_slice]
print(subset)
# Result: [2, 3, 4]
# Create a slice object to represent a slice from the beginning to index 3 (exclusive)
our_slice = slice(None, 3)
subset = our_list[our_slice]
print(subset)
# Result: [0, 1, 2]
# Create a slice object to represent a slice from index 5 to the end of the list
our_slice = slice(5, None)
subset = our_list[our_slice]
print(subset)
# Result: [5, 6, 7, 8, 9]
# Create a slice object to represent a slice of every second element
our_slice = slice(None, None, 2)
subset = our_list[our_slice]
print(subset)
# Result: [0, 2, 4, 6, 8]

When you want to package a slicing process to reuse it several times or send it as an argument to methods that need a slice object, the slice() function can be helpful.

Python Examples for slice() 

Python slicing string variables

Code:

our_text = "Hello, World!"
our_slice = slice(7)  # Create a slice object for the first 7 characters
substring = our_text[our_slice]
print(substring)  # Output: "Hello, "

Python Slicing Lists or Arrays

Code:

our_list = [0, 1, 2, 3, 4, 5, 6]
our_slice = slice(2, 5)  # Create a slice object from index 2 to 5 (exclusive)
subset = our_list[our_slice]
print(subset)  # Output: [2, 3, 4]

Python Slicing Tuples

Code:

our_tuple = (10, 20, 30, 40, 50)
our_slice = slice(1, 4)  # Create a slice object from index 1 to 4 (exclusive)
subset = our_tuple[our_slice]
print(subset)  # Output: (20, 30, 40)

Python Slicing using Negative Indexing

Code:

our_text = "Hello, World!"
our_slice = slice(-6, None)  # Create a slice object for the last 6 characters
substring = our_text[our_slice]
print(substring)  # Output: "World!"

Python slice() To Get Sub-Tuple Using Negative Indexing

Code:

our_tuple = (10, 20, 30, 40, 50)
our_slice = slice(-3, None)  # Create a slice object for the last 3 elements
subset = our_tuple[our_slice]
print(subset)  # Output: (30, 40, 50)

Python slice() Example to Slice Strings With Indexing Syntax

Code:

our_text = "Python Programming"
our_substring = our_text[7:18]  # Slice from index 7 to 18 (exclusive)
print(our_substring)  # Output: "Programming"

Python Slice() Example to Slice a List Using Indexing Syntax

Code:

our_list = [10, 20, 30, 40, 50]
subset = our_list[1:4]  # Slice from index 1 to 4 (exclusive)
print(subset)  # Output: [20, 30, 40]

Python Slice() Example for Slicing and Modifying a List

Code:

our_list = [0, 1, 2, 3, 4, 5]
# Modify a slice of the list
our_list[2:4] = [9, 8]
print(our_list)  # Output: [0, 1, 9, 8, 4, 5]

Conclusion

To sum up, Python slicing is a flexible and strong tool that enables you to extract, modify, and interact with particular parts of sequences like strings, lists, and tuples. It gives you precise control over the elements you can access and change. Python programmers who are proficient in slicing can handle a variety of data sets and tackle a variety of programming problems.

FAQs

1. What happens if the start or stop of a slice is missed?

Start defaults to 0 (the start of the series) if you omit it. Stop defaults to the length of the sequence (the end of the sequence) if you omit it in Python slicing.

2. How do you cut a sequence in half to get the nth element in Python slicing?

You can set the step parameter to n to obtain a sequence's nth element. The expression my_list[::3] pulls the third element from each row in the list.

3. What occurs when a slice's start index is higher than its stop index?

The slice will produce an empty sequence if the start index is higher than the stop index. My_list[5:2] will, for instance, produce an empty list.

Leave a Reply

Your email address will not be published. Required fields are marked *