Understanding copy on modify with subsets of lists

If we create a list, then a copy of that list:

l1 <- list(1,2,3)
l2 <- l1

We can use lobstr to see that the two lists have the same reference

identical(lobstr::ref(l1),lobstr::ref(l2))
> TRUE

And can confirm this even further, using the first element in each list:

lobstr::obj_addr(l1[[1]]) == lobstr::obj_addr(l2[[1]])
> TRUE

BUT my mental model breaks down when we start looking at subsets of the list since shouldn't these too be identical?

identical(lobstr::obj_addr(l1[1]), lobstr::obj_addr(l2[1]))
> FALSE

I'm even further confused by their unique references since these are identical above.

lobstr::ref(l1[1], (l2[1]))

Any ideas? Thanks!

I think the confusion is caused by lack of square brackets to unwrap from list

 identical(lobstr::obj_addr(l1[[1]]), lobstr::obj_addr(l2[[1]]))
#[1] TRUE

I think when you use single square bracket, the value 1 is wrapped in a new list that is created for you on the fly. this will have a unique address

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.