How do I append to list only after a certain value in another python list?

Viewed 391

I have 2 lists. I only want to append to the new list after I've reached the specified value.

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'

The desired outcome is:

new_list = ['banana', 'grape']

I've tried this, but the result is not what I want:

for i in old_list:
    if i != value:
        new_list.append(i)

Hope that makes sense!

5 Answers

Use the list.index method to return the index i where the value appears in the old_list. Then slice old_list from index i+1 up to its end:

old_list = ['apple', 'pear','orange', 'banana', 'grape']
value  = 'orange'

i = old_list.index(value)
new_list = old_list[i+1:]

You can try to use a boolean to check if 'orange' has been passed through.

Try this:

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'

checker = False

for i in old_list:
  if checker:
    new_list.append(i)
  if i == value:
    checker = True

Hope This Helped You

There are a lot of ways to do it. Without knowing what you have tried, here is one way:

i = old_list.index('orange')
i = i + 1

while i < len(old_list):
    new_list.append(old_list[i])
    i = i + 1

Finding the index of 'orange' and then looping through the remaining values in old_list and appending them into new_list.

Using the itertools module,

from itertools import dropwhile


def takeafter(iterator, value):
    itr = dropwhile(lambda x: x != value, iterator)
    try:
        next(itr)
    except StopIteration:
        pass
    return itr


old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'

new_list.extend(takeafter(old_list, value))

dropwhile creates an iterator that starts producing values from its input once the predicate is true. As we don't want that first item, either, we use next to advance passed the starting value before returning the iterator.

You could make a if statement that checks if the first list includes your "specified value", then append to the next list.

if not, it would append to the first list.

for example

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'

if value in old_list:
   new_list.append('banana', 'grape')

else:
   old_list.append('banana', 'grape')

Haniel

Related