How to Split a List at the First Occurrence of a Value in Python
This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.
Python code
16 linesdef split_at_first(lst, value):
try:
idx = lst.index(value)
return lst[:idx], lst[idx:]
except ValueError:
return lst, []
if __name__ == "__main__":
sample = [1, 2, 3, 4, 3, 5]
value = 3
left, right = split_at_first(sample, value)
print("Left:", left)
print("Right:", right)
sample2 = [1, 2, 3]
left2, right2 = split_at_first(sample2, 9)
print("Not found →", left2, "|", right2)
Output
Left: [1, 2]
Right: [3, 4, 3, 5]
Not found → [1, 2, 3] | []
How it works
The list.index() method finds the index of the first occurrence of the value. Slicing with lst[:idx] grabs everything before that index, and lst[idx:] includes the value and everything after. If the value isn't present, index() raises ValueError, which the function catches to return the original list and an empty list. This approach avoids manual loops and is both concise and efficient.
Common mistakes
- Forgetting that `index()` raises `ValueError` instead of returning -1.
- Using `lst.split()` which is for strings, not lists.
- Slicing with `lst[:idx]` and `lst[idx+1:]` accidentally excluding the value.
- Assuming the value appears only once when the function handles duplicates correctly.
Variations
- Use a generator with `next()` to find the index without exceptions.
- Loop manually with `enumerate()` to split if you need to avoid exceptions.
Real-world use cases
- Splitting an email header from its body at the first blank line.
- Separating configuration arguments from positional parameters in a CLI parser.
- Dividing a log stream into a prefix segment and the remainder for analysis.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.