k4rli
k4rli

Reputation: 120

Finding the index of the first element of a list in another list

main_list = ['4', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
my_list = ['4', '5', '6']

My question is, how to find index of my_list in main_list?

The integers in my_list must be in consecutive order in main_list.

I tried using main_list.index(my_list[0]) but if there are more than one of a specific element, it returns the wrong index number. The result I need to get is 4, however with main_list.index(my_list[0]) it'll just give 0 as its index.

If there is any need for clarification, I can edit the post with additional details. Sorry, English is not my first language.

Upvotes: 1

Views: 80

Answers (4)

Anas Khan
Anas Khan

Reputation: 98

A much more effective one liner :

print ','.join(main_list).find(','.join(my_list)) - ''.join(main_list).find(''.join(my_list))

Converts them to strings with the elements separated by commas, finds the occurrence, then subtracts the occurrence found when the commas aren't there, and you have your answer.

Upvotes: 0

Rohin Gopalakrishnan
Rohin Gopalakrishnan

Reputation: 664

You can convert both lists into a string using join() function and iteratively compare the strings to find a match.

EDIT: Made a change for it two work for multi-digit numbers. Added a float case as well.

For example:

main_list = ['4', '1', '2', '3', '40.1', '52', '61', '7', '8', '9', '10']
my_list = ['40.1', '52', '61']
index = -1

for i in range(len(main_list)):
    if '#'.join(main_list[i:i+len(my_list)]) == '#'.join(my_list):
        index = i
        break

print(index)

Upvotes: 1

Simon Callan
Simon Callan

Reputation: 3130

Try something like this

for i in range(len(main_list)-len(my_list)):
    if main_list[i:i+len(my_list)] == my_list:
        index = i 
        break

This should work for all possible types that could go in the lists.

Upvotes: 2

ForceBru
ForceBru

Reputation: 44838

If you would like an algorithm solution:

def Find(haystack, needle):
    n, h = len(needle), len(haystack)
    assert n <= h

    for i in range(h):
        if h - i <= n: break
        count = 0
        for i_, j in zip(range(i, i + n), range(n)):
            if haystack[i_] == needle[j]:
                count += 1
        if count == n: return i

    return -1

Upvotes: 0

Related Questions