Marcos Rusiñol
Marcos Rusiñol

Reputation: 105

Create a new list that contains the following values of certain words from another list

I need to create a new list that contains the following values ​​of certain words from another list.

I mean, I have a list:

 list = ['KAZES', 'CAR', 'MOTOR', 'TWO', 'SAINT', 'MOTOR', 'DOMAIN', 'BARCELONA']

And I want to create a list ONLY with the next values of the word 'MOTOR'. Like that:

 Motor = ['TWO','DOMAIN']

Upvotes: 0

Views: 76

Answers (3)

mattjegan
mattjegan

Reputation: 2884

I rename your list to ls since list shadows a python builtin function. My approach is to loop over the current list and if we encounter the search word, we check to make sure we aren't at the end of the list, and then add the next item to the final list.

searchWord = 'MOTOR'

final = []
for i, e in enumerate(ls):
    if e == searchWord:
        if i + 1 < len(ls):
            final.append(ls[i + 1])

Hope I helped.

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137408

This is untested:

def next_after (seq, key):
    it = iter(seq)
    while True:
        if next(it) == key:
            yield next(it)

result = list(next_after(my_orig_list))

Upvotes: 0

perigon
perigon

Reputation: 2095

For a one-line solution using a list comprehension:

motor = [lst[i+1] for i, word in enumerate(lst[:-1]) if word == 'MOTOR']

I renamed two of your variables: list to lst because list is a Python built-in, and Motor to motor because Python convention is lowercase variable names.

Upvotes: 5

Related Questions