login about faq

I'm curious, how to best explain why when you do:

R = []
R.append(3)

and you do this:

P = R
R.append(4)

why does P's (as an obj) also gets R's values:

(the numbered list represent each line)

  1. R = []
  2. R.append(3)
  3. P = R
  4. R.append(4)
  5. print P

It says: [3, 4]

asked Sep 12 '11 at 20:02

whatever's gravatar image

whatever
1.1k1329

edited Sep 13 '11 at 10:02

Randell's gravatar image

Randell ♦♦
1.6k1529


The line

P = R

Just performs reference assignment. It doesn't clone or copy the object(s). This is the same behavior in a lot of popular languages, including C/C++, Java and Ruby.

You can think of it as simply declaring another 'name' (or reference) for the object 'held' by the current variable named R. Both variables P and R now refer to the same object.

Note that primitive variables behave differently from variables containing references to objects, which is likely the source of your confusion. In Ruby, for example:

a = 1    # a => 1
b = a    # b => 1
a += 1   # a => 2
b        # b => 1
link

answered Sep 13 '11 at 10:00

Alistair%20A.%20Israel's gravatar image

Alistair A. Israel
3.1k210

edited Sep 13 '11 at 21:29

2

+1 on the "it's how practically all mainstream languages do it".

Ruby nitpicking, though: Ruby doesn't have a ++ operator, and doing the += only makes the incrementing appear like an operation on primitives by creating a copy of the object.

A better way to show that all entities in Ruby are objects/references is:

a = "test string"
b = a
puts b      # outputs "test string"
a.reverse
puts b      # outputs "test string"
a.reverse!
puts b      # outputs "gnirts tset"
(Sep 13 '11 at 12:22) Bryan Bibat Bryan%20Bibat's gravatar image

Python's objects are all pass by reference. If you need to pass by value you can do:

from copy import deepcopy
...
P = deepcopy(R)
link

answered Sep 12 '11 at 22:53

Marconi's gravatar image

Marconi
9289

edited Sep 12 '11 at 22:54

It's not even about "pass by reference". He's just doing reference copying, not object 'cloning' or deep copying as you've noted.

(Sep 13 '11 at 07:01) Alistair A. Israel Alistair%20A.%20Israel's gravatar image

Yes I know, I was giving an example on how you might mimic pass by value.

(Sep 13 '11 at 10:16) Marconi Marconi's gravatar image
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or __italic__
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×24

Asked: Sep 12 '11 at 20:02

Seen: 426 times

Last updated: Sep 13 '11 at 21:29