pythonlistfor-looplexicographic

What's printed by the following Pyhon code?


animals = ['horse', 'Pig', 'dog', 'Owl', 'lion', 'Hare', 'baboon', 'Fish', 'tiger', 'Zebra', 'Cow', 'Mouse', 'quail', 'Elephant']

for animal in animals:

    if (animal >= 'M') and (animal <= 'Z'):

        print(animal)

Question 1:

How to understand (animal >= 'M') and (animal <= 'Z') ?

Question 2:

The correct answer is Pig Owl Mouse, why Zebra is not printed in this case?


Solution

  • Like zvone pointed out, string are compared alphabetically and therefor Zebra is not printed.

    The alphabetic order in this case would be.

    X Y Z Za Zebra