Maxwell Gyimah
Maxwell Gyimah

Reputation: 43

Clarifying use of an already declared variable within a for loop that iterates through a list

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

Answers (3)

Dadep
Dadep

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

Aaron
Aaron

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

U13-Forward
U13-Forward

Reputation: 71580

Let me explain step by step:

  • You first iterate through the list ['Giraffe','Alligator','Liger'], which will give you Giraffe the first iteration, and so on...
  • Then you get the minimum value of the string (who would want to do that :P), which is 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 ords of the values.
  • The last line will give the maximum value of the 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

Related Questions