Remove element of list until getting to the first empty one in Python

Viewed 489

I have this list of strings

list = ['1', '2', '3', '4', '', '    5', '    ', '    6', '', '']

and I want to get every item after the first empty string to get this result

list = ['    5', '    ', '    6', '', '']

note that I want to leave the empty strings that comes after

I wrote this function:

def get_message_text(list):
    for i, item in enumerate(list):
        del list[i]
        if item == '':
            break
    return list

but I am getting this wrong results for no reason I know:

['2', '4', '    5', '    ', '    6', '', '']

any help ?

2 Answers

Just find the index of the first empty string and slice on it:

def get_message_text(lst):
    try:
        return lst[lst.index("") + 1:]
    except ValueError:  # '' is not in list
        return [] # if there's no empty string then don't return anything

Construct a generator that drops while empty string not yet found.

Use list(get_message_text(lst)) if you need a list,

otherwise use generator in for expression

for e in get_message_text(lst):

def get_message_text(lst):
    output = False
    for e in lst:
        if not output:
            if e == '': output = True
            continue
        yield e
Related