[Tutor] iterate list items as lvalue

Dave Kuhlman dkuhlman at rexx.com
Mon Aug 20 22:32:48 CEST 2007


On Mon, Aug 20, 2007 at 03:14:24PM -0300, Ricardo Ar?oz wrote:

[snip]
> > You just work on a generated modified list.
> > 
> > foo = range(1,6)
> > for i in [x*2 for x in foo]:
> >    do_whatever_you_want_with(i)
> > 
> 
> What about :
> 
> array = [1,2,3,4,5]
> array = [i * 2 for i in array]
> 

Good solution.

However, consider the following:

    >>> array = [1,2,3,4,5]
    >>> array2 = array
    >>> array = [i * 2 for i in array]
    >>> array
    [2, 4, 6, 8, 10]
    >>> array2
    [1, 2, 3, 4, 5]

So, did you want array2 to change, or not?

Your solution is a good one for situations where you do *not* want
array2 to change.

Here is a solution that changes the object that both array and
array2 refer to:

    >>> array = [1, 2, 3, 4, 5]
    >>> array2 = array
    >>> for idx, item in enumerate(array):
        array[idx] = item * 2
    >>> array
    [2, 4, 6, 8, 10]
    >>> array2
    [2, 4, 6, 8, 10]

Basically, this modifies the list "in place", rather than making a
new list from the old one.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list