Best way to have a for-loop index?
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Fri Mar 10 19:28:25 EST 2006
On Thu, 09 Mar 2006 20:22:34 -0500, Roy Smith wrote:
>> My question is, is there a better, cleaner, or easier way to get at the
>> element in a list AND the index of a loop than this?
>>
>> TIA,
>> Andrew
>
> The real question is *why* do you want the index?
>
> If you're trying to iterate through list indicies, you're probably trying
> to write C, C++, Fortran, Java, etc in Python.
That's a bit harsh, surely? Well-meaning, but still harsh, and untrue.
Wanting to walk through a list replacing or modifying some or all items in
place is not unpythonic. Sure, you could simply create a new list:
L = [1, 2, 3, 4]
newL = []
for item in L:
if item % 3 == 0:
newL.append(item)
else:
newL.append(item**2)
but that's wasteful if the list is big, or if the items are expensive to
copy.
Isn't this more elegant, and Pythonic?
L = [1, 2, 3, 4]
for index, item in enumerate(L):
if item % 3 != 0:
L[index] = item**2
--
Steven.
More information about the Python-list
mailing list