2

For example, I am iterating through a dictionary mydict as follows:

mydict = {"Name" : "Vincent Vega", "Profession" : "Gangster", "Age" : "42"} for k in mydict: print k, mydict[k] 

Now, k is just a looping variable that I didn't even declare. How does the compiler know that by k, I mean the keys of the dictionary?

2 Answers 2

6

The for statement use a special method (__iter__ and next) on the object, here mydict.

Each iteration produce a result, stored in the variable k

For a dictionary, the __iter__ method returns the keys of the dictionary.

More info here.

Sign up to request clarification or add additional context in comments.

Comments

1

The for loop calls iter() on the sequence that is looped over, and uses next() calls on the result.
Different objects can return different iterators with different behaviors and that's why at one time you will see it iterate over keys of a dictionary and another time an index of array, depending on the iterable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.