Python slice() Built in Function

The slice() function in Python returns a slice object that can be used to slice any sequence (string, tuple, list, range or bytes). The syntax is:

slice(start, stop, step)

where start is the starting index of the slice (inclusive), stop is the ending index of the slice (exclusive) and step is the increment between each index. If any of these parameters are omitted, they default to None.

Here are some examples of using slice() with different sequences:

# Create a string
my_string = "Python Programming"

# Use slice() to get a substring

sliced_string = slice(7) # equivalent to slice(None, 7, None)
print(my_string[sliced_string]) # Output: Python

# Use slice() with negative indices
sliced_string = slice(-4, -1) # equivalent to slice(-4, -1, None)
print(my_string[sliced_string]) # Output: ing

# Use slice() with step parameter
sliced_string = slice(0, 12 ,2) # equivalent to slice(None ,12 ,2)
print(my_string[sliced_string]) # Output: Pto rg

# Create a list

my_list = [1 ,2 ,3 ,4 ,5 ,6]

# Use slice() to get a sublist
sliced_list = slice(2 ,5) # equivalent to slice(2 ,5 ,None)
print(my_list[sliced_list]) # Output: [3 ,4 ,5]

# Use slice() with negative step parameter
sliced_list = slice(-1 ,-7 ,-2) # equivalent to slice(-1 ,-7 ,-2)
print(my_list[sliced_list]) # Output: [6 ,4 ,2]

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions