user2572329
user2572329

Reputation: 35

Search list between specific index in Python

I need to create a function that will search for a list-item between specific indexes.

I want to have a start and stop index for the list, I want to find the position of the item in the list.

For example:

def find(list, word, start=0, stop=-1):
    print("In function find()")

    for item in list:
        if item == word:
            return list[start:stop].index(word)

n_list = ['one', 'five', 'three', 'eight', 'five', 'six', 'eight']
print(find(n_list, "eight", start=4, stop=7 ))

This code will return "2", because the word "eight" is in the index position of 2 in list[4:7].

My question: How can I change this code so that it returns "6"? If I remove the [4:7], it's giving me "3" because the word "eight" is also in the [3] position.

Edit: forgot to say thank you!

Upvotes: 0

Views: 4895

Answers (3)

Moses Koledoye
Moses Koledoye

Reputation: 78556

The for loop is not needed:

def find(list, word, start=0, stop=-1)
    '''Find word in list[start:stop]'''
    try:
       return start + list[start:stop].index(word)
    Except ValueError:
       raise ValueError("%s was not found between indices %s and %s"%(word, start, stop))

Upvotes: 0

Zafi
Zafi

Reputation: 629

If you assume that the range characterized by start and stop can be trusted you can make it into a one-liner:

n_list[start:stop].index(word)+start

Upvotes: 1

Can't you simply add start?

def find(list, word, start=0, stop=-1):
print("In function find()")

for item in list:
    if item == word:
        return start + list[start:stop].index(word)

Upvotes: 2

Related Questions