Reputation: 43
I don't understand why after declaring the variable animal as the string 'Peacock', you are able to use it in the for loop such that it outputs the smallest character in each list element. What does animal in the for loop represent?
I originally thought it would check if the string peacock was in the list element, and then print out the smallest character. I am looking for a general explanation of how this code works if possible.
The output for this code is: G A L r
animal='Peacock'
for animal in ['Giraffe','Alligator','Liger']:
print(min(animal))
print(max(animal))
Upvotes: 0
Views: 175
Reputation: 2788
declare a variable call animal
:
animal='Peacock'
now you erase the content of your variable animal which will contain successively 'Giraffe'
then 'alligator'
and then 'Liger'
as it will become successively each element of the list:
for animal in ['Giraffe','Alligator','Liger']:
print(min(animal))
print(max(animal))
to understand better you can run:
animal='Peacock'
print(animal)
for animal in ['Giraffe','Alligator','Liger']:
print(animal)
Upvotes: 1
Reputation: 459
What you are doing here is actually finding the minimum character in each of the list: Meaning, since G has the lowest precedence in 'Giraffe', G is printed out.
Example given
Upvotes: 0
Reputation: 71580
Let me explain step by step:
['Giraffe','Alligator','Liger']
, which will give you Giraffe
the first iteration, and so on...G
, then A
, then L
, since when you get the ord(your number here)
of them and it get's the minimum from the list of ord
s of the values.animal
, which is the last element since that exits the loop, so the maximum value of Liger
is r
, since it's ord
is the biggest.So that's the reason, also Peacock
gets out of your code after it is overwritten.
Upvotes: 2