-1

If I have a list:

my_list = ['hey', 'how are', 'you', 'Bob', 'Jim']

and I want to remove all elements from the list following:

if 'Bob' in my_list:
    print(my_list)

Such that the output is:

my_list = ['hey', 'how are', 'you']

which removes ['Bob', 'Jim']

excelsior
  • 95
  • 1
  • 9

2 Answers2

-1

You can try this:

my_list = ['hey', 'how are', 'you', 'Bob', 'Jim']

if 'Bob' in my_list:
    bob_index = my_list.index("Bob")  #Get index of Bob
    my_list[bob_index:len(my_list)] = [] #Remove everything from Bob onwards
    print(my_list)

Output:

['hey', 'how are', 'you']
Hari
  • 718
  • 3
  • 9
  • 30
-2

It's unclear whether you want to just not display (print) after the string is found or actually remove all of them from the list.

Here's how you could do each operation:

my_list = ['hey', 'how are', 'you', 'Bob', 'Jim']

# Output strings up to 'Bob'.
try:
    stop = my_list.index('Bob')
except ValueError:
    stop = len(my_list)
print(my_list[:stop])


# Remove strings from 'Bob' onward.
try:
    del my_list[my_list.index('Bob'):]
except ValueError:
    pass
print(my_list)
martineau
  • 119,623
  • 25
  • 170
  • 301