0

Sorry if this is a really easy question, but I've been going through control flows in the python documentation and something confuses me that it doesn't address.

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
     print i, a[i]

When I type that in, it prints the result;
0 Mary
1 had
2 a
3 little
4 lamb

Something also odd was that when I typed "a", I get 'lamb'.

What my question here is that 'i' was never defined here. When I try another letter, or assign 'i' as a variable, I just get an error. What exactly is this and is there anything else like that I should know?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by npn_
1

Lets break it down.

IDLE 2.6.2      
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in a:
	print i
	
Mary
had
a
little
lamb

>>> for item in a:
	print item
	
Mary
had
a
little
lamb

>>> #So it can be anything you whant(i,item,element.....)
>>> #The for loop iterates over elemen in a

>>> i = 'Mary'
>>> i
'Mary'
>>> i = 'had'
>>> i
'had'
>>> i = 'a'
>>> i
'a'

>>> #So the for loop assigning each element in a to i
>>> for i in range(5):
	print i
	
0
1
2
3
4
>>> len(a)
5
>>> #So the last part that you have combine this 2
>>>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.