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)
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)
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.