I have the first two strings in a string list strs
that is guaranteed to have length of at least 2. I want to compare their letters against each other, and perform a task when their letters are identical. Here is the code I am using:
iter_len = len(strs[1])
if (len(strs[0]) >= len(strs[1])):
iter_len = len(strs[0])
for i in range (0, iter_len, 1):
if (strs[0][i] == strs[1][i]):
[do a thing]
However, when I run this, I get a IndexError: string index out of range
for the if (strs[0][i] == strs[1][i]):
line. I don't quite understand why this is happening, as the first if
statement should ensure that iter_len
is the minimum length between strs[0]
and strs[1]
, and should prevent the index from going over. Any advice is much appreciated.
CodePudding user response:
If you need to iterate through two sequences in lockstep, it's generally best practice to use zip
:
for a,b in zip(strs[0], strs[1]):
if a == b:
#[do a thing]
This will deal with the issue of one sequence being longer than the other.
If you need the index, you can use enumerate
with your zip
:
for i, (a, b) in enumerate(zip(strs[0], strs[1])):
if a == b:
#[do a thing with i]