0
a = [10, 23, 56, [78]]
b = list(a)
a[3][0] = 95
a[1] = 42
print(b)

So, I am printing b here, not a. While getting an output only the nested list part seems to be changed in b while everything else remains unchanged:

a is now [10, 42, 56, [95]]  # [95] was changed in a and b, but 23  
b is now [10, 23, 56, [95]]  # did not change to 42 in b - only in a

Can someone please explain me what's happening?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Vamps
  • 17
  • 5
    Have you seen [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) by Ned Batchelder? That's a pretty good article that will hopefully answer the question. – decorator-factory May 31 '22 at 11:34
  • Using `list` creates a ***shallow*** copy of the argument list. So changing `a[1]` will not be reflected, but both `a[3]` and `b[3]` point to ***the same list*** – Tomerikoo May 31 '22 at 11:37
  • another duplicate (less votes) but almost identical to this post: https://stackoverflow.com/questions/17873384/how-to-deep-copy-a-list – OrenIshShalom May 31 '22 at 11:39
  • References (list, dict, set, ...) vs. Values ... and not understanding that `list(a)` does not deepcopy all things (in case you wanted [78] to stay intact in b. Looking for a dupe .... Numbers are "values" and copied by a shallow copy - a shallow copy will only copy the referece to [78] to the new list - hence pointing to the same data – Patrick Artner May 31 '22 at 11:39
  • 1
    @OrenIshShalom this is a typical tripping point for newly minted python devs - there are at least a hundred possible dupe candidates :) addded yours – Patrick Artner May 31 '22 at 11:40

0 Answers0