Python slice list by value | Example code

Using bisect methods can slice list by value in Python. Python conveniently has a bisect module as part of the standard library.

Python slice list by value example

Simple example code slicing a list based on value.

import bisect

data = [1, 3, 5, 6, 8, 9, 11, 13, 17]
value = 9

pos = bisect.bisect_right(data, value)

res = data[:pos]
print(res)

Output:

Python slice list by value

Another example using if statement

v = 5
l = [1, 3, 5, 8, 9, 11, 13, 17]
if v in l:
    # do stuff
    print(l[:l.index(v)])

Output: [1, 3]

Do comment if you have any doubts and suggestions on this Python slice topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.