By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,713 Members | 764 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,713 IT Pros & Developers. It's quick & easy.

How do I change elements in a list?

P: n/a
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...
Nov 6 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On Nov 6, 3:11 pm, "Just Another Victim of the Ambient Morality"
<ihates...@hotmail.comwrote:
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...pes/lists.html
http://docs.python.org/lib/built-in-funcs.html

Mike

Nov 6 '07 #2

P: n/a
Dan
On Nov 6, 4:11 pm, "Just Another Victim of the Ambient Morality"
<ihates...@hotmail.comwrote:
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[i] += 1
>>first
[2, 3]
>>second
[2, 3]

-Dan

Nov 6 '07 #3

P: n/a
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
Nov 6 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.