Skip to content
Advertisement

Last element of list not being taken into account for if statement

I’m an absolute beginner at python and I need to write a code which can differentiate between 2 lists. Overall code works yet, consistently the last element of the list is not being taken into account and lists such as “AT, AC” are being considered the same. I would love some help. Thanks !

Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")

seq1 = list(Seq1)
seq2 = list(Seq2)

def compare_seq(seq1,seq2):
 if len(seq1) != len(seq2):
  print(" The sequences differ by their length ")
  exit()
 else:
  for i in range(len(seq1)) :
   if seq1[i] == seq2[i]:
    print(" The sequences are the same ")
    exit()
   else :
    print(" Sequences differ by a/mulitple nucleotide ")
    exit()

compare_seq(seq1,seq2)

Advertisement

Answer

You exit the loop too early which is a common mistake:

for i in range(len(seq1)) :
    if seq1[i] == seq2[i]:
        print(" The sequences might be the same ")  # note "might"
        # exit()  # <- leave this one out
    else:
        print(" Sequences differ by a/mulitple nucleotide ")
        exit()
print(" The sequences are the same ")  # now you know

There is a built-in shortcut for this pattern (all) which you can combine with zip to make this more concise:

# ...
else:    
    if all(x == y for x, y in zip(seq1, seq2)):
        print(" The sequences are the same ")
    else:
        print(" Sequences differ by a/mulitple nucleotide ")

for lists, you can also just check equality:

if seq1 == seq2:
    print(" The sequences are the same ")
elif len(seq1) != len(seq2):
    print(" The sequences differ by their length ")
else:
    print(" Sequences differ by a/mulitple nucleotide ")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement