I didn't see anyone responding to this, so I'll pop in here...

On 03/22/2016 04:05 AM, BartC wrote:
[...]
(Suppose you need both the value and its index in the loop? Then the one-line 
for above won't
work. For example, 'something' is [10,20,30] and you want to print:

  0: 10
  1: 20
  2: 30 )


Your lack of knowledge of Python is showing again...
Python has "enumerate" just for this purpose.  Your example would be written as:

for i, val in enumerate(something):
    print('{}: {}'.format(i, val))

However, in this specific example, the i is not used as an actual index but rather a line-number. So you can change "enumerate(something)" to "enumerate(something, 1)" to set the starting number to 1 instead of the default 0, and the lines will be numbered 1, 2 and 3 rather than 0, 1 and 2.

As always, the choice is yours.  ;-)


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to