-1

I have this below code

a = [1,2,3]
b = a
a is b #shows True

b = a[:]
a is b #shows False
a == b # shows True

I thought the value of [1,2,3] and a[:] would have the same id and they are the exact same object. What exactly happens when a[:] is assigned to b? I'm sorry if this question has already been asked before, could not find a perfect answer

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Py_learner
  • 53
  • 8

1 Answers1

1

a[:] is a shallow copy of a list (as a slice). It has the same numeric value, but it is not the original list. == Checks value, "is" is value and "identity" of the value.

polymerchm
  • 188
  • 1
  • 7
  • Since it doesn't look like you've taken the tour yet, I'll clue you: please don't answer no-brainer questions like this until you check to see if it's a duplicate. If it hasn't already been answered go for it, but if it has flag it to be closed instead. – Jared Smith Nov 04 '19 at 17:54
  • @TankorSmash I know, which is why I left a comment and didn't downvote/flag it. Although I see someone did. Ah well. – Jared Smith Nov 04 '19 at 18:08
  • Thanks. The word "shallow copy" helped me understand the reason behind the difference. – Py_learner Nov 04 '19 at 19:03