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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

16 lines
Python 3.9+
def 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

stdout
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

  1. Use a generator with `next()` to find the index without exceptions.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.