I have a list, ls = [0 1 2 3 4]
and I am running the following:
print(ls is ls[:])
I am getting the output as False
. Why are they not the same list? When I print both versions I get the same list printed.
I have a list, ls = [0 1 2 3 4]
and I am running the following:
print(ls is ls[:])
I am getting the output as False
. Why are they not the same list? When I print both versions I get the same list printed.
ls
references one object in memory; ls[:]
creates a new list
object using the same references contained in the first.
>>> ls = [0, 1, 2, 3, 4]
>>> new_ls = ls[:]
>>> id(ls) == id(new_ls)
False
>>> id(ls[0]) == id(new_ls[0])
True
This is basically a duplicate of
String comparison in Python: is vs. ==
You just didnt know it.
==
and is
check two different things.
==
asks are these two thing the same value.
is
asks are these two things the same thing i.e. the same object.
a[:]
copies the list creating a new list with the same value.
thus
a == a[:]
>> True
a is a[:]
>> False
[:]
creates a shallow copy of ls
, which destroys the new list's original reference to ls
. Bear in mind, however, that nested lists are not effected by [:]
and thus, copy.deepcopy
is required.
Example:
s = [5, 6, 2, 4]
=>s
[5, 6, 2, 4]
new_s = s
new_s.append(100)
=>new_s
[5, 6, 2, 4, 100]
=>s
[5, 6, 2, 4, 100]
Usage of deepcopy
:
s = [5, 6, [5, 6, 2, 4], 4]
new_s = s[:]
new_s[2].append(45)
=>s
[5, 6, [5, 6, 2, 4, 45], 4] #both sublists are still being referenced
=>new_s
[5, 6, [5, 6, 2, 4, 45], 4]
import copy
s1 = [5, 6, [5, 6, 2, 4], 4]
new_s1 = copy.deepcopy(s1)
new_s1[2].append(100)
=>new_s1
[5, 6, [5, 6, 2, 4, 100], 4]
=>s1
[5, 6, [5, 6, 2, 4], 4]
[:]
denotes slicing of a list (slice from start till end) which creates a shallow copy of your iterable object.
To demonstrate further:
When you create a list a = [1]
and do b = a
, here you are simply reassigning name of a to b where a and b both point o same memory address
>>> a = [1,2]
>>> b = a
>>> id(a)
140177107790232
>>> id(b)
140177107790232
>>> b.remove(1)
>>> a
[2]
But if you do it with slicing:
>>> a = [1,2]
>>> b = a[:]
>>> id(a)
140177107873232
>>> id(b)
140177107873304
>>> b.remove(1)
>>> a
[1, 2]
>>>