0

I'm working on a project for my Python course and I'm still pretty new to coding in general. I'm having issues with one of the snippets of my code. I'm trying to make Python find every instance of the word "the" (or any input word really, it doesn't matter.) and return the word immediately after it. I am able to make it return the word after "the", but it stops after one instance when I need it to scan the entire list.

Here is my code:

the_list=['the']
animal_list=['the', 'cat', 'the', 'dog', 'the', 'axolotl']

for the_list in animal_list:
    nextword=animal_list[animal_list.index("the")+1]
    continue

print(nextword)

All I'm returning is cat whereas dog and axolotl should pop up as well. I tried using a for loop and a continue in order to make the code go through the same process for dog and axolotl, but it didn't work.

Mazdak
  • 105,000
  • 18
  • 159
  • 188

7 Answers7

0

I am not clear what you are asking for, but I think what you want is to get the animals that are in the list animal_list, and assuming that the word 'the' is in the even indeces, you can use this;

animals = [animal for animal in animal_list if animal != 'the']

Since you are a beginner, the previous code uses a comprehension which is a pythonic way to iterate over a loop without a for loop, the equivalent code to the previous one using a for loop is:

animals = []

for animal in animal_list:
    if animal != 'the':
        animals.append(animal)
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
0

index only will get the first instance. The typical pythonic way is to use a list comprehension:

[animal_list[i+1] for i,val in enumerate(animal_list) if val=='the']
jeff carey
  • 2,313
  • 3
  • 13
  • 17
0

list.index will only find the first occurrence, however you can specify a start and stop value to skip over other indexes.

Now we also need to use a try/except block because list.index will raise a ValueError in the case that it doesn't find a match.

animal_list=['the', 'cat', 'the', 'dog', 'the', 'axolotl']
match = 'the'

i = 0
while True:
    try:
        i = animal_list.index(match, i) + 1 # start search at index i
    except ValueError:
        break

    # can remove this check if certain that your list won't end with 'the'
    # otherwise could raise IndexError
    if i < len(animal_list):
        print(animal_list[i])

However in case you don't have to use list.index, I would suggest the following instead. (Again can remove the check if list won't end with 'the'.

for i, item in enumerate(animal_list):
    if item == match and i + 1 < len(animal_list):
        print(animal_list[i + 1])

Or more compact is to use list comprehension. Which will output a list of all items after 'the'.

animals = [ animal_list[i + 1] for i, v in enumerate(animal_list)
            if v == match and i + 1 < len(animal_list) ]
print(animals)

Note: The use of continue is not correct. continue is used when you want to end the current iteration of the loop and move on to the next. For example

for i in range(5):
    print(i)
    if i == 2:
        continue
    print(i)

# Output
0
0
1
1
2 # Notice only '2' is printed once
3
3
4
4
Steven Summers
  • 5,079
  • 2
  • 20
  • 31
0

Try this:

the_list=['the']

animal_list=['the', 'cat', 'the', 'dog', 'the', 'axolotl']
i=0
for i in range(len(animal_list)):
    if animal_list[i] in the_list:
        nextword=animal_list[i+1]
        print nextword
kat il
  • 1
  • 1
0

One approach is to zip the list to a shifted version of itself:

keyword = 'the'
animal_list=['the', 'cat', 'the', 'dog', 'the', 'axolotl']
zipped = zip(animal_list, animal_list[1:])
# zipped contains [('the', 'cat'), ('cat', 'the'), ('the', 'dog') etc.]

found_words = [after for before, after in zipped if before == 'the']

This will deal with a list that ends in 'the' without raising an error (the final 'the' will simply be ignored).

Stuart
  • 9,597
  • 1
  • 21
  • 30
0

This is a very UN-PYTHONIC way of doing this...but perhaps it'll help you understand indexes:

animal_list = ['the', 'cat', 'the', 'dog', 'the', 'axolotl']
index=0

for x in animal_list:
  if x == "the":
    print(animal_list[(index + 1)])
  index +=1
gregory
  • 10,969
  • 2
  • 30
  • 42
0
the_word = 'the'
animal_list = ['the', 'cat', 'the', 'dog', 'the', 'axolotl']

# Iterate through animal_list by index, so it is easy to get the next element when we find the_word
for i in range(len(animal_list) - 1):
    if animal_list[i] == the_word:       # if the current word == the word we want to find
        print(animal_list[i+1])          # print the next word

We dont want to check the last element in animal_list. That is why I subtract 1 from the length of animal_list. That way i will have values of 0, 1, 2, 3, 4.

Cory
  • 1