Hey guys,

I don't understand the for loop. Could someone explain it to me?

for example

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)
... 
cat 3
window 6
defenestrate 12

what is x? how does 'x' know what to measure?

'for' loops iterate through a sequence, such as a string or list, and does stuff with it.

For example, in your given code

a = ["cat", "window", "defenstrate"]

for x in a:
    print x, len(x)

'for' initiates the loop. The next variable (which happens to be x) after 'for' will be created automatically, and will take on the first item in the following sequence, in this case the variable 'a'.

In the 'for' block, it tells python to print 'x', and show the len(x). The newly created x has taken on the first item in 'a': 'cat'. So its just like saying "print 'cat', len(cat)".

After it finishes the block, it goes back up to the 'for', and 'x' takes on the next item in the sequence: 'window', and does the same thing it did with 'cat'. The for loop keeps repeating until it has gone through all of the items in the sequence.

You can also do it with strings as well.

>>> string = "Hi there"
>>> for s in string:
	print s

	
H
i
 
t
h
e
r
e

Ok thanks alot I understand now.
thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.