goelakash
goelakash

Reputation: 2519

Index of first differing element without loop

I have two lists say

A = [1,3]
B = [1,3,5,6]

I want to know the index of the first differing element between these lists (2 in this case).

Is there a simple way to do this, or do I need to write a loop?

Upvotes: 2

Views: 108

Answers (2)

Rockybilly
Rockybilly

Reputation: 4520

Perhaps the loop you mentioned is the most obvious way, not necessarily the most pretty. Still every O(n) complexity solution is fine by me.

lesser_length = min(len(A), len(B))
answer = lesser_length # If one of the lists is shorter and a sublist, 
                       # this will be the answer, because the if condition
                       # will never be satisfied.
for i in xrange(lesser_length):
    if A[i] != B[i]:
        answer = i
        break

range instead of xrange in Python3. A generator would be the best way given that you don't know when the difference between lists will occur.(In Python2, xrange is generator. In Python3, xrange became the regular range() function.)

A list comprehension is also viable. I find this to be more readable.

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107347

You can use following generator expression within next() function using enumerate() and zip() function:

>>> next(ind for ind,(i,j) in enumerate(zip(A,B)) if i != j)
2

Upvotes: 5

Related Questions