How do I change elements in a list?

  • Thread starter Just Another Victim of the Ambient Morality
  • Start date
J

Just Another Victim of the Ambient Morality

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...
 
K

kyosohma

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
 
D

Dan

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...
first = [1,2]
second = first
for i in range(len(first)):
first += 1
[2, 3]

-Dan
 
B

Bruno Desthuilliers

Just Another Victim of the Ambient Morality a écrit :
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.

first = [1,2]
second = first
first[:] = [i+1 for i in first]

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top