1

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?

1
  • 1
    I see no reason for this question to have been -1d. +1d to compensate. Commented Nov 6, 2011 at 11:48

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

print ’demolist[’,c,’]=’,demolist[c] prints the string "demolist[", the value of c, the string "]=", and the value of demolist[c], separated by spaces.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.