Using iterators to write in the structure being iterated through?

Pierre Barbier de Reuille p.barbierdereuille at free.fr
Fri Jul 28 17:18:17 EDT 2006


Pierre Thibault wrote:
> On Wed, 26 Jul 2006 18:54:39 +0200, Peter Otten wrote:
> 
>> Pierre Thibault wrote:
>>
[...]
> 
> Now, I want to do simple math operations on the data in C. Doing a loop
> from 0 to 49 would loop twice through the actual data. In this
> context, an iterator is perfect since it can take care internally of going
> through the data only once, so it would be great to access _AND MODIFY_
> data over which I iterate.
> 

The biggest problem I think is that numbers are immutable in Python.
Thus you cannot modify a number if you have a variable on it! All you
can do is modify the content of the variable.

IMHO, the way to go is to iterate on the indices and not on the values
(not much slower in Python). For example you can do something like:

lst1 = [1,2,3,4]
lst2 = [4,3,4,5]

for i in xrange(len(lst1)):
  lst1[i] += lst2[i]

If you *really* want to iterate (for example to support something else
that lists), then you will need to create a new structure like that:

from itertool import izip

lst1 = MyList1()
lst2 = MyList2()

result = [0]*len(lst1) # If possible

for i,(e1,e2) in enumerate(izip(lst1, lst2)):
  result[i] = e1+e2

lst1[:] = result # If you really need it

An intermediate possibility would be (if lst1 is indexable):

for i,e2 in enumerate(lst2):
  lst1[i] += e2

But it all depend on the kind of structure you get.

Pierre



More information about the Python-list mailing list