11.3 Arrays and Lists in Memory
In Understanding Equality, we drew memory diagrams to show how values appear in the heap. At that time, we looked only at structured data. Now we will look at aggregate data: lists in Python and arrays in Pyret.
Python |
|
|
|
Pyret |
|
|
Directory
-
sl
→ 1001
Heap
-
1001:
(length:3)
-
1002:
"bread"
-
1003:
"coffee"
-
1004:
"eggs"
sl
followed by an offset: for instance,
Python |
Pyret |
|
|
sl
, then
add 1 and the offset 2
to it”. This produces the address
1001 + 1 + 2 = 1004. Looking up the value stored
at address 1004, in both languages, produces
'eggs'
.You may find it odd that the offsets begin
at 0. While it is indeed confusing—0
, the “third” value at offset 2
, and so on—'tea'
. Recall that the second
value is at offset 1
:
Python |
Pyret |
|
|
sl
, which is 1001; add
1 and the offset (1
) to it; this gives us the address
1003. Now, we modify the value at 1003 to be the new
value:
Directory
-
sl
→ 1001
Heap
-
1001:
(length:3)
-
1002:
"bread"
-
1003:
"tea"
-
1004:
"eggs"
|
|
|
and in Pyret,
|
|
|
sl
is Shaunae’s and Jonella writes:
Python |
Pyret |
|
|
jl
and sl
are aliases for the same data in the heap:
Directory
-
sl
→ 1001 -
jl
→ 1001
Heap
-
1001:
(length:3)
-
1002:
"bread"
-
1003:
"tea"
-
1004:
"eggs"
jl
has the same impact as modifying it
via sl
:
Python |
Pyret |
|
|
Directory
-
sl
→ 1001 -
jl
→ 1001
Heap
-
1001:
(length:3)
-
1002:
"butter"
-
1003:
"tea"
-
1004:
"eggs"
jl
, we will see in Python:
|
|
|
and in Pyret:
|
|
|
even though we did not make a modification through the name sl
.