Python aliasing [duplicate] - python

This question already has answers here:
If two variables point to the same object, why doesn't reassigning one variable affect the other?
(4 answers)
Are Python variables pointers? Or else, what are they?
(9 answers)
Closed 2 years ago.
I understand that given this code
a = [1,2,3]
b = [4,5,6]
c = a
and then by doing this
a[0] = 0
I wil change first positions of both a and c. Could somebody explain why this doesn't apply when I do this:
a = b
ie. why c doesn't become equal to b?

a = [1,2,3]
b = [4,5,6]
# a ────────> [1,2,3]
# b ────────> [4,5,6]
c = a # Changing 'c' to point at the list that 'a' points at
# c ─────┐
# a ─────┴──> [1,2,3]
# b ────────> [4,5,6]
a = b # Changing 'a' to point at the list that 'b' points at
# c ─────┐
# a ──┐ └──> [1,2,3]
# b ──┴─────> [4,5,6]

Because python interprets the line of code from the beginning of the code to the bottom line. Therefore, you have been assigned the b to a, after assigning a to c. The value of c is not changed until reassigning c.

Related

A list assignment problem, that has been messing with my code [duplicate]

This question already has answers here:
Changing one list unexpectedly changes another, too [duplicate]
(5 answers)
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 8 months ago.
could someone explain why this thing exists and how to counteract it
a = [1, 2, 3]
b = a
b[1] = 0
print(a)
a = [1, 0, 3]
Its bugging me, because, when I use this with int, then it acts normally.
a = 1
b = a
b +=1
print(a)
a = 1
It`s really messing with some of my code
Thanks in advance
By doing b = a you are having both point to the same spot in memory. Thus, changes to one will reflect in the other.
A simple fix to copy an array without them being connected:
b = a[:]
b = a is making b a reference to the same list as a. Use
b = a.copy()
to make a separate list.

Why Python can achieve a, b = b, a [duplicate]

This question already has an answer here:
How does swapping of members in tuples (a,b)=(b,a) work internally?
(1 answer)
Closed 1 year ago.
If we need to swap variables a and b in C or Java, we need to have something (pseudo code) like:
tmp = a;
a = b;
b = tmp;
Why Python can do it by a, b = b, a. What happened with it?
Not sure whether it is the right place for this question. But I do appreciate it if someone could give me some clues.
It's because python provides a special "tuple unpacking" syntax that many other languages don't have. I'll break apart what's going on:
The b, a on the right of the equals is making a tuple (remember, a tuple is pretty much the same as a list, except you can't modify it). The a, b on the left is a different syntax that's unpacking the tuple, i.e. it takes the first item in the tuple, and store it in the first variable listed, then it takes the second item and stored it in the second variable, and so forth.
This is what it looks like broken up in multiple steps:
a = 2
b = 3
my_tuple = a, b
print(my_tuple) # (2, 3)
b, a = my_tuple
print(a) # 3
print(b) # 2
And here's another, simpler examples of tuple unpacking, just to help wrap your mind around it:
x, y, z = (1, 2, 3)
print(x) # 1
print(y) # 2
print(z) # 3
By the way, Python's not the only one, Javascript can do it too, but with arrays:
[a, b] = [b, a];

python fibonacci - what is the difference? [duplicate]

This question already has answers here:
Python variable assignment question
(6 answers)
Closed 6 years ago.
I am learning python and I have some question:
What is the difference between
a,b = 0,1
for x in range(100):
print(a)
a=b
b=a+b
and
a,b = 0,1
for x in range(100):
print(a)
a,b = b, a+b
First one gives bad result, but why?
Because you first set a = b, your new b will have the value of twice the old b. You overwrite a to early. A correct implementation should use a temporary variable t:
a,b = 0,1
for x in range(100):
print(a)
t=a
a=b
b=t+b
This is basically what you do by using sequence assignment.
In your original code you have:
a,b = 0,1
for x in range(100):
print(a)
a=b # a now is the old b
b=a+b # b is now twice the old a so b'=2*b instead of b'=a+b
So this would result in jumping by multiplying with two each time (after first loading in 1 into a the first step).
An equivalent problem is the swap of variables. If you want a to take the value of b and vice versa, you cannot write:
#wrong swap
a = b
b = a
Because you lose the value of a after the first assignment. You can use a temporary t:
t = a
a = b
b = t
or use sequence assignment in Python:
a,b = b,a
where a tuple t = (b,a) is first created, and then assigned to a,b.

How variables are passed in a Python function? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Create a copy and not a reference of a NumPy array
(1 answer)
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 7 years ago.
If I run the following code in Python 2.7, I get [2., 2., 2.] printed for both a and b. Why does b change together with a? Many thanks!
def test_f(x):
a = np.zeros(3)
b = a
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
Because b and a are referring to the same list in memory. b = a does not create a new copy of a.
Try this and see the difference:
def test_f(x):
a = np.zeros(3)
b = a.copy()
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
b = a.copy() will create a new copy that exactly resembles the elements of a, whereas b=a just creates a new reference to the exisiting list.
numpy will use a pointer to copy unless you tell it otherwise:
import numpy as np
def test_f(x):
a = np.zeros(3)
b = np.copy(a)
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
[ 2. 2. 2.]
[ 0. 0. 0.]

Not sure what does shadow copy of a list mean here? A reference? Not sure why some vaules changed/ unchanges [duplicate]

This question already has answers here:
What is the difference between shallow copy, deepcopy and normal assignment operation?
(12 answers)
Closed 7 years ago.
a = [ 1, 2, [3,4] ]
b = list(a) # create a shallow copy of a
c = a
print (b is a) # False
print (c is a)
b.append(100) # append element to b
print (b)
print (a) # a is unchanged
print (c)
c.append(100) # append element to c
print (b) # b is unchanged
print (a)
print (c)
b[2][0] = -100 # modify an element inside b
print (b)
print (a) # a is changed
print (c)
c[2][0] = -200
print (b) # b is changed
print (a) # a is changed
print (c)
As a beginner in python, I'm not sure what is the meaning of shadow copy, why b.append cannot change a, why c.append cannot change b, why b[2][0] can change a, and why c[2][0] can change b. Thank you!
This is happening because shallow copy b contains references to the list [3,4].
So when you do b[2][0] = -100 then since b is having the reference of the nested list hence both a and b gets affected. If you had done deep copy the list [3,4] would be created again in memory and it will be pointed by b
Due to above reason c[2][0] also changes b since c is also pointing to the same list as a

Categories