How do I change elements in a list?
kyosohma at gmail.com
kyosohma at gmail.com
Tue Nov 6 16:20:21 EST 2007
On Nov 6, 3:11 pm, "Just Another Victim of the Ambient Morality"
<ihates... at hotmail.com> wrote:
> How do you change certain elements in a list? I'm looking to do the
> Python equivalent of this Ruby code:
>
> -> first = [1, 2]
> => [1, 2]
> -> second = first
> => [1, 2]
> -> first.map! {|i| i + 1}
> => [2, 3]
> -> first
> => [2, 3]
> -> second
> => [2, 3]
>
> I need to change a list, in place, so other variables referencing that
> list also see the change.
> Thank you...
You can "point" one variable name at another so that they both
reference the same list:
second = first
To change a list "in place", I usually do something like this:
first[someElement] = something-else
or
# change the first element in the list
first[0] = 55
See also
http://docs.python.org/tut/node7.html
http://www.diveintopython.org/native_data_types/lists.html
http://docs.python.org/lib/built-in-funcs.html
Mike
More information about the Python-list
mailing list