Python built-in Method - slice()

The slice() function is a built-in Python method that is used to create a slice object. A slice object is a representation of a range of indices that can be used to extract a portion of a sequence or a mapping.

The syntax for the slice() function is as follows:

slice(stop)
slice(start, stop[, step])
Source:w‮tfigi.ww‬idea.com
  • start: The starting index of the slice.
  • stop: The stopping index of the slice.
  • step: The step size of the slice.

Here are some examples of how the slice() function can be used:

>>> lst = [1, 2, 3, 4, 5]
>>> s = slice(2)
>>> print(lst[s])
[1, 2]

In this example, we create a list lst with five elements. We then create a slice object s that includes the first two elements of the list using the slice() function. Finally, we use the slice object to extract the first two elements from the list.

>>> s = slice(1, 4, 2)
>>> print(lst[s])
[2, 4]

In this example, we create a slice object s that includes every other element starting from the second element and ending with the fourth element of the list. Finally, we use the slice object to extract every other element from the list.

>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> keys = slice('a', 'c')
>>> print(list(dct[keys].values()))
[1, 2]

In this example, we create a dictionary dct with three key-value pairs. We then create a slice object keys that includes the keys from 'a' to 'c' using the slice() function. Finally, we use the slice object to extract the values of the key-value pairs with keys 'a' and 'b' from the dictionary.

The slice() function is a useful built-in method in Python that provides a convenient way to create a slice object that can be used to extract a portion of a sequence or a mapping. The slice object can be used with a variety of built-in methods and data types, including lists, tuples, strings, and dictionaries.