In Python, slice() is used to access a portion of a sequence such as a list or tuple. It helps improve code readability and maintainability by giving meaningful names to slices instead of using hardcoded indices. For example: slice(1, 5, 2) corresponds to a[1:5:2] and slice(1, 4) corresponds to a[1:4].
Slicing Lists with slice()
Consider a case where we need to display students' names, phone numbers, and addresses along with their average marks and without naming slices the code becomes hard to maintain when the structure changes hence it is advised to use slice whenever required.
Python
li = [('Student A', 9876543210, 'Address of A', 99, 82, 97, 78, 69),
('Student B', 9999999999, 'Address of B', 90, 83, 87, 72, 67),
('Student C', 8888888888, 'Address of C', 88, 41, 56, 61, 93)]
# Naming slices for clarity
details = slice(0, 3)
marks = slice(3, 8)
# Display name, address, phone no., and average marks
for student in li:
print(student[details], "Marks:", sum(student[marks])/5)
Output('Student A', 9876543210, 'Address of A') Marks: 85.0
('Student B', 9999999999, 'Address of B') Marks: 79.8
('Student C', 8888888888, 'Address of C') Marks: 67.8
Explanation:
- details = slice(0, 3) creates a slice for the first three elements (name, phone number, and address).
- marks = slice(3, 8) creates a slice for the marks (from the 4th to the 8th element).
Syntax of slice:
- slice(stop)
- slice(start, stop, step)
Parameters:
- start: Starting index where the slicing of object starts.
- stop: Ending index where the slicing of object stops.
- step: It is an optional argument that determines the increment between each index for slicing.
- Return Type: Returns a sliced object containing elements in the given range only.
Handling Large Datasets with slice()
Whenever we have to deal with large datasets then using hardcoded slice indices can make the code difficult to understand that is why using slice() allows for better flexibility and easier changes in the data structure. For instance consider this scenario: If we decide to add a new entry (e.g., "Roll no") at the beginning of each tuple then code with hardcoded indices would need to be updated everywhere and by naming slices, the code can remain unchanged even if the dataset structure changes.
Python
# New data structure with 'Roll no' at index 1
li = [('Student A', 123, 9876543210, 'Address of A', 99, 82, 97, 78, 69),
('Student B', 124, 9999999999, 'Address of B', 90, 83, 87, 72, 67),
('Student C', 125, 8888888888, 'Address of C', 88, 41, 56, 61, 93)]
# Update slice to reflect new structure
details = slice(1, 4) # Adjusting for the new 'Roll no' index
marks = slice(4, 9)
# Displaying updated details
for student in li:
print(student[details], "Marks:", sum(student[marks])/5)
Output(123, 9876543210, 'Address of A') Marks: 85.0
(124, 9999999999, 'Address of B') Marks: 79.8
(125, 8888888888, 'Address of C') Marks: 67.8
Using slice() with Iterables Other Than Lists
slice() function is not limited to lists; it can be used with other iterable objects like tuples and strings. This is useful when working with sequences where direct indexing may not be ideal.
Python
# using slice with tuple
tup = ('Student A', 9876543210, 'Address of A', 99, 82, 97, 78, 69)
details = slice(0, 3)
marks = slice(3, 8)
print(tup[details], "Marks:", sum(tup[marks])/5)
# using slice with string
s = "Hello, World!"
substring = slice(7, 12)
print(s[substring])
Output('Student A', 9876543210, 'Address of A') Marks: 85.0
World
Similar Reads
How To Slice A List Of Tuples In Python? In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read
Slice a 2D List in Python Slicing a 2D list in Python is a common task when working with matrices, tables, or any other structured data. It allows you to extract specific portions of the list, making it easier to manipulate and analyze the data. In this article, we'll explore four simple and commonly used methods to slice a
4 min read
Python - Frequency of K in sliced String Given a String, find the frequency of certain characters in the index range. Input : test_str = 'geeksforgeeks is best for geeks', i = 3, j = 9, K = 'e' Output : 0 Explanation : No occurrence of 'e' between 4th [s] and 9th element Input : test_str = 'geeksforgeeks is best for geeks', i = 0, j = 9, K
6 min read
Slice a 2D Array in Python We are given a 2D array matrix and we have to Slice this matrix 2D array and return the result. In this article, we will see how we can Slice the 2D array in Python. Example Input : matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output : [[ 4, 5, 6]] Explanation : We can see that 2D array (matrix) is
3 min read
How to Split Lists in Python? Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read