As you know Python List is a collection that is ordered and changeable. if you don’t know then you must read the first Python List tutorial. Python List Slicing is a way to get a range of items in a list.
Note: List are index from 0 to size-1, with a step of 1.
A syntax is where to start the slicing, where to end and specify the step.
Python list slice Examples
Let’s do multiple example of it.
1. Basic Example
Let’s do the basic example of list slicing.
L = ['a', 'b', 'c', 'd'] print(L[2:3])
2. Slice with Negative Indices
Example of passing negative indices while slicing a list.
L = ['a', 'b', 'c', 'd'] print(L[-7:-2])
Output: [‘a’, ‘b’]
3. Slice with Positive & Negative Indices
Using positive and negative indices at the same time in slice function.
L = ['a', 'b', 'c', 'd'] print(L[1:-2])
4. Specify Step of the Slicing
The step parameter is optional and by default 1 and its used for specify the step.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(L[2:9:2])
Output: [3, 5, 7, 9]
5. Slice List at Beginning & End in Python
Omitting the start index starts the slice from the index 0. Meaning,
L[:stop] is equivalent to
L = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(L[:3])
Output: [1, 2, 3]
Q: How do Python slice list by value?
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])
Do comment if you have any suggestions and doubts on this tutorial.
IDE: PyCharm 2020.1.1 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.