Reputation: 47
The following code:
c=0 while c < len(demolist):
print ’demolist[’,c,’]=’,demolist[c]
c=c+1
Creates this output:
demolist[ 0 ]= life
demolist[ 1 ]= 42
demolist[ 2 ]= the universe
demolist[ 3 ]= 6
demolist[ 4 ]= and
demolist[ 5 ]= 7
demolist[ 6 ]= everything
What's up with the demolist[',c,']
format that is being printed in the while loop? Why does this give a number in the brackets, whereas putting demolist[c]
there just prints that exactly?
Upvotes: 1
Views: 11638
Reputation: 22619
c
is an integer. demolist[c]
returns the value at index c
from the list, demolist
.
print ’demolist[’,c,’]=’
prints the series of objects, with an implicit conversion to a string (which is why you don't need to explicitly convert c (an integer) to a string).
A better way of writing this code is
for idx, item in enumerate(demolist):
print 'demolist[%d] = %s' % (idx, item)
Upvotes: 1
Reputation: 837946
The print statement receives four arguments (separated by commas):
’demolist[’ # string
c # integer
’]=’ # string
demolist[c] # result of list access
A clearer way to write that line is:
print 'demolist[ {0} ]= {1}'.format(c, demolist[c])
See it working on line: ideone
Note: You may also want to consider using enumerate
here instead of a while loop.
for n, elem in enumerate(demolist):
print 'demolist[ {0} ]= {1}'.format(n, elem)
See it working on line: ideone
Upvotes: 5
Reputation: 18633
print ’demolist[’,c,’]=’,demolist[c]
prints the string "demolist["
, the value of c
, the string "]="
, and the value of demolist[c]
, separated by spaces.
Upvotes: 2