Home > Enterprise >  list index out of range-comparing two lists of different length
list index out of range-comparing two lists of different length

Time:03-12

I am new to Python. How do I compare two lists of different lengths? I want to print "substitute" if two characters don't match, "delete" if second list character is empty, and "insert" if first list character is empty.

str1 = "ANNA"
str2 = "ANA"

list1 = list(str1)
list2 = list(str2)

for i in range(len(list1)):
    if list1[i] != list2[i]:
        print("substitute")
    elif len(list2[i]) == 0:
        print("insert")
    else:
        print("delete")

CodePudding user response:

The way to modify your current script would be to avoid attempting to run off the end of list2 as that's what's triggering the error:

# Note, strings can be accessed like a list with []
str1 = "ANNA"
str2 = "ANA"

for i in range(min(len(str1), len(str2))):
    if str1[i] != str2[i]:
        print("substitute")
    else:
        print("delete")
for _ in range(max(0,len(str1)-len(str2))):
    print("insert")

A slightly more python-ic way would be to ask for forgiveness rather than permission with a try/catch:

for i, c1 in enumerate(str1):
    try:
        if c1 != str2[i]:
            print("substitute")
        else:
            print("delete")
    except IndexError:
        print("insert")

or if you don't like exceptions, the cleaner way would be to use some of the itertools. Here I'll use zip_longest which returns None for the cases where there is no object in the shorter list

from itertools import zip_longest

for a, b in zip_longest(str1, str2):
    if not b:
        print("insert")
    elif a == b:
        print("delete")
    else:
        print("substitue")

CodePudding user response:

you need to check the feature of str as a sequential container.

Please check following code.

str1 = "ANNA"
str2 = "ANA"

## you don't need to make str to list. str is a container
####list1 = list(str1)
####list2 = list(str2)

if not str1 and not str2 :   # empty str is logically false
    print('substitute')
else:
    print( 'insert' if str2 else 'delete' )
##    # followings can replace above print()
##    if str2:    
##        print('insert')
##    else:
##        print('delete')

    # you may need this function
    if str2:
        str1 = str2
    else:
        str1 = ''  # this can remove all characters in str

##    # this if statement is same with following line
##    str1 = str2
##
 

  • Related