Python slice function returns a slice object that can use used to slice strings, lists(Array), tuple, etc. Means slice object is used to specify how to slice a sequence like strings, lists, tuples.
Syntax
slice(start, stop, step)
Parameters
- start – The slicing of the object starts. Optional and Default is NONE.
- stop – The slicing stops at index stop -1 (last element) and it’s required.
- step – Determines the increment between each index for slicing. Optional and Default is NONE.
Return value:
It returns a slice object.
Example of Python slice Function
Let’s do coding:-
Create a slice object
# contains indices (0, 1, 2) obj1 = slice(3) print(obj1) # contains indices (1, 3) obj2 = slice(1, 5, 2) print(slice(1, 5, 2))
Output:
slice(None, 3, None)
slice(1, 5, 2)
1. String slicing
Example of python slice string. First create a slice object and then use to it slice string. Passing only stop value.
# String slicing str = 'Hello World' s_obj = slice(5) print(str[s_obj])
Output: Hello
Read more: Python slice string Examples
2. List slicing
Lst = [1, 2, 3, 4, 5] s_obj = slice(3) print(Lst[s_obj])
Output: [1, 2, 3]
Read more: Python list slice | Get specific sets of sub-elements Array
3. Tuple slicing
Same as String and list you can slice tuple:-
# Tuple slicing Tup = (1, 2, 3, 4, 5) s_obj = slice(3) print(Tup[s_obj])
Output: (1, 2, 3)
Python slice shorthand | Understanding slice notation
Slice notation is used to extract a substring.
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
There is also the step
value, which can be used with any of the above:
a[start:stop:step] # start through not past stop, by step
List Slicing Shorthand
li = ['a', 'b', 'Python', 'z', 'Tutorial'] print(li[:3]) print(li[3:]) print(li[:])
Output:
[‘a’, ‘b’, ‘Python’]
[‘z’, ‘Tutorial’]
[‘a’, ‘b’, ‘Python’, ‘z’, ‘Tutorial’]
::-1 python Slice Notation
You can now easily extract the elements of a list that have even indexes:
This also works for List, arrays, and strings:
# Tuple slicing Tup = (1, 2, 3, 4, 5) print(Tup[::2])
Output: (1, 3, 5)
Q: How to Python slice list by value
Answer: Use bisect
module as part of the standard library. See the below example for slice the list by value in python.
import bisect lst = [1, 3, 5, 6, 8, 9, 11, 13, 17] for val in range(19): pos = bisect.bisect_right(lst, val) print(val, '->', lst[max(0, pos - 3):pos])
Output:
Python list slice loop
This code snippet to be very interesting.
a = [0, 1, 2, 3] for a[-1] in a: print(a)
Output:
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
Do comment if you have any doubts and suggestion on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.