Python Forum

Full Version: for loop execution
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I python documentation I found the below code and it's output -

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb


But in while I am practising in python 3.6 and going through the same code I am getting some different format output. The code along with the output is given below -

>>> word
['dog', 'window', 'cat', 'window']
>>> for i in range(len(word)):
... print(i,word[i])
...
(0, 'dog')
(1, 'window')
(2, 'cat')
(3, 'window')


Please ensure me which one should I follow, the documented one or the output that I am getting because it is of some different formatted.
I can't reproduce your output.

$ python
Python 3.6.3 (default, Oct 24 2017, 14:48:20)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> words = ['dog', 'window', 'cat', 'window']
>>> for i in range(len(words)):
...     print(i, words[i])
...
0 dog
1 window
2 cat
3 window
>>> 
A refference link?[/i]
Python 3 produces the following:
>>> word = ['dog', 'window', 'cat', 'window']
>>> for i in range(len(word)):
...     print(i,word[i])
...
0 dog
1 window
2 cat
3 window
>>>
Python 2, on the other hand, produces this:
>>> word = ['dog', 'window', 'cat', 'window']
>>> for i in range(len(word)):
...     print(i,word[i])
...
(0, 'dog')
(1, 'window')
(2, 'cat')
(3, 'window')
>>>
If you are producing the second version you are not using python3 (even if you think you are).
Since when the print in Python 2 is a function, not a statement?  I will try it right away Shy
That is the point, it isn't a function.
It is printing the parenthesis because syntactically you are asking it to print a tuple.
Wow, the space between print and the parenthesis is missing and that confuses me.

Anyway, we do the same that way.

>>> words = ['dog', 'window', 'cat', 'window']
>>> for index, word in enumerate(words):
...     print index, word
...
0 dog
1 window
2 cat
3 window
https://docs.python.org/2/library/functions.html#enumerate