Can anyone explain how x is taking integer values. We are directly using x in for loop “for x in a”
How is the compiler going to recognize it that x represents the strings inside the list?
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
forworks differently in Python than it works in languages like C. Instead of counting up/down a numerical value and checking an end condition as you usually would in C:it iterates over all the elements in the container (whose name is referenced after the
in):Its precise behavior depends on the type of container (
iterable) used; in a list or tuple, it will start at the first element, then move through the list/tuple one item at a time until the final element has been reached. Each of the elements will be then referenced by a name (itemin this example) so that it can be operated on in the body of the loop.In a dictionary,
forwould iterate through the dictionary’s keys (in an unspecified order), soitemwould contain a key of the dictionary.In a string, it iterates through the letters of the string, one by one. Etc.