Some hypothetical questions which puzzle me


#1



I got the exercise right, but I have a conceptual question which I don't quite understand.

In the bit about the use of the "for" loop, it is stated that you can use for variable in list_name: in order to do something with every item in the list.

An example given was:

animals = ["cat", "ant", "bat"]
animals.sort()

for animal in animals:
    print animal

So I am wondering about 2 things:

  1. Does this mean that Python can recognise any variable name I choose? Like for example, if I have a list called cities with 3 strings in it ie. cities = ["London", "Singapore", "Tokyo"] and I want to use the for loop ie. for city in cities: , will Python recognise it?

  2. If I have something like sheep = ["Andy", "Mandy", "Dandy"] and I type for sheep in sheep: , will Python recognise it? I know that I can use for names in sheep: as an alternative, but I am just curious about how things will work.

Thank you :slight_smile:


#2

The list contains items, not variables.

animal is a local variable to the for block that acts as a placeholder for the list items, each in turn.

Yes, and that is probably a good way to write it, singular in plural.

No, since sheep cannot be a key name of itself. Sucks, but you would have to use 'sheeps'.