2

I am writing a function that takes two strings as parameters, turns them in lists, and then returns an index of where the two strings differ:

def ss(line1,line2):
    count = 0
    list1 = line1.split()
    list2 = line2.split()
    for word in list1:
        if word is not list2[count]:
            return count
        else:
            count += 1

ss("Why is this not working?", "Why is this not working?")

The output I get is that my count is whatever I set it to initially (e.g., "0"). As far as I can see, it should be updating the count and then reiterating through the lists to compare the next indexes?

What do I not understand about how for-loops work?

Thanks.

9000
  • 39,899
  • 9
  • 66
  • 104
neuroNerd
  • 23
  • 5
  • 1
    Possible duplicate of [Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?](https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce) – Daniel Pryden Jan 22 '18 at 17:47

1 Answers1

2

The issue is that you are using != instead of is not.

Explanation:

  • The is keyword in Python compares object identity. Every string in Python is it's own separate object and thus, it's own separate identity. So when you use the is keyword with two strings it will not check the actual contents.

  • However, to compare the contents of an object or variable you can use == or != which return True or False.

I hope this answer helped you and if you have any further questions please feel free to post a comment below!

Micheal O'Dwyer
  • 1,237
  • 1
  • 16
  • 26