Search code examples
pythonlistloopspython-itertools

How can I compare for equality the values of two lists in one loop?


So I want to make this so I can check if another code is working, but I keep getting this error:

'list index out of range'

For the following code:

for L1[i] in range(0, len(L1)):
    if L1[i]==L2[i]:
        L1[i]='ok'

What is going wrong?


Solution

  • Assuming this is Python, there are two problems:

    1. You only want to specify i in the beginning of the for-loop.
    2. L2 may not have as many items as L1.

    for i in range(0, len(L1)):
        try:
            if L1[i] == L2[i]:
                L1[i] = 'ok'
        except IndexError:
            break
    

    As Frederik points out, you could use enumerate as well:

    for i, l1 in enumerate(L1):
        try:
            if L[i] == L2[i]:
                L1[i] = 'ok'
        except:
            break
    

    In my opinion, the increase in readability of enumerate over range is mostly offset by defining an extra variable (l1) which you never use. But it is just my opinion.


    One last option, which may be best, is to use zip to merge the two lists (zip truncates the longer of the two):

    for i, l1, l2 in enumerate( zip(L1, L2) ):
        if l1 == l2:
            L1[i] = 'ok'