1

I want to split the following list into sub lists based on an element from that list.

    array=['first','sentence','step','second','sentence']
    for i in array:
        if i!='step':
            newlist1.append(i)
        else:
            (stop appending in newlist1 and start appending in say newlist2)

newlist1 and newlist2 can not be pre declared. As the number of elements in the array can vary. SO I need to find a dynamic way of declaring lists as per the requirement.

Anas Baig
  • 13
  • 1
  • 3

4 Answers4

1

you could use a list of lists to store these. So if the value is step then start a new list, if not then append to the last list.

from pprint import pprint

lists = [[]]
array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'thrid', 'step', 'some', 'other', 'sentance']
for i in array:
    if i == 'step':
        lists.append([])
    else:
        lists[-1].append(i)
pprint(lists)

OUTPUT

[['first', 'sentence'],
 ['second', 'sentence'],
 ['thrid'],
 ['some', 'other', 'sentance']]
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
0

You can do the following:

array=['first','sentence','step','second','sentence']
newlist1 = []
newlist2 = []
check = True
for i in array:
    if i!='step' and check:
        newlist1.append(i)
    else:
        check = False
        newlist2.append(i)
  • This doesn't adhere to the OPs requirements that: the new lists be created dynamically as the original is of arbitrary length. It also ignores the clarification comment that 'step' be removed from the result. – Sam Aug 08 '21 at 20:05
0

Try this

index = array.index('step') 
if index and index < len(array):
    newlist1 = array[0:index+1]
    newlist2 = array[index+1:]
Visakh B Sujathan
  • 229
  • 1
  • 4
  • 25
  • This doesn't adhere to the OPs requirements that: the new lists be created dynamically as the original is of arbitrary length. It also ignores the clarification comment that 'step' be removed from the result. – Sam Aug 08 '21 at 20:01
0

Although less memory efficient than Chris Doyle's answer, I prefer comprehensions for stuff like this unless they get too verbose to fit on one line.

array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'third', 'step', 'some', 'other', 'sentence']

def split_list(lst, sep):
    return [i.split() for i in ' '.join(lst).split(sep)]

print(split_list(array, 'step'))

Result

[['first', 'sentence'], ['second', 'sentence'], ['third'], ['some', 'other', 'sentence']]

Bonus

If the end goal is a list of sentences instead of a list of lists, just replace the first .split() with .strip().

[i.strip() for i in ' '.join(lst).split(sep)]

Returns:

['first sentence', 'second sentence', 'third', 'some other sentence']
Sam
  • 69
  • 1
  • 10