The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Larry Hudson orgnut at yahoo.com
Wed Mar 23 01:17:13 EDT 2016


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.  ;-)





More information about the Python-list mailing list