Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Python splitting list to sublists at given start/end keywords

If I were to have a list, say

lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']

I'd like to split it into a sublist with 'foo' and 'bar' as start and end keywords, so that I would get

lst = ['hello', ['foo', 'test', 'world', 'bar'], 'idk']

The way I am currently doing this is as follows.

def findLoop(t):   
    inds = [index for index, item in enumerate(t) if item in ["FOO", "BAR"]]
    centre = inds[(len(inds)/2)-1:(len(inds)/2)+1]
    newCentre = t[centre[0]:centre[1]+1]
    return t[:centre[0]] + [newCentre] + t[centre[1]+1:]

def getLoops(t):
    inds = len([index for index, item in enumerate(t) if item in ["FOO", "BAR"]])
    for i in range(inds):
        t = findLoop(t)
    return t

This looks a bit messy, but it works very well for nested start/end keywords, so sublists can be formed inside of sublists, but it does not work for multiple start/end keywords not being inside eachother. Being nested is not important yet, so any help would be appreciated.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

One way using slicing:

>>> lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
>>> a=lst.index('foo')    # locate start word
>>> b=lst.index('bar')+1  # locate end word
>>> lst[a:b] = [lst[a:b]] # replace list slice with a list of the slice
>>> lst
['hello', ['foo', 'test', 'world', 'bar'], 'idk']
over 4 years ago · Santiago Trujillo Report

0

multiple start,ends (based on Mark Tolonen's answer)

lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk','am']
t = [('foo','test'),('world','idk')]

def sublists(lst, t):
    for start,end in t:
        a=lst.index(start)
        b=lst.index(end)+1
        lst[a:b] = [lst[a:b]]
    return lst

print(sublists(lst,t)) 

Returns:

 ['hello', ['foo', 'test'], ['world', 'bar', 'idk'], 'am']
over 4 years ago · Santiago Trujillo Report

0

Using slicing, without support for nested lists:

>>> lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
>>> start_idx = lst.index('foo')
>>> end_idx = lst.index('bar')
>>> lst[:start_idx] + [lst[start_idx:end_idx+1]] + lst[end_idx+1:]
['hello', ['foo', 'test', 'world', 'bar'], 'idk']
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!