Skip to content

Python slice list by value | Example code

  • by

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

Python slice list by value example

A simple example is 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 an 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 or suggestions on this Python slice topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading