pangna
pangna

Reputation: 61

In what manner do list and array differ while storing values?

I am reading a book Fluent Python by Luciano Ramalho published by O'Reilly. In chapter two the author presents an interesting statement defining container sequences and flat sequences.

Container sequences: list, tuple, and collections.deque can hold items of different types.

Flat sequences: str, bytes, bytearray, memoryview, and array.array hold items of one type.

and then he goes on saying that:-

Container sequences hold references to the objects they contain, which may be of any type, while flat sequences physically store the value of each item within its own memory space, and not as distinct objects. Thus, flat sequences are more compact, but they are limited to holding primitive values like characters, bytes, and numbers.*

This got me thinking that if lists store references to the objects they are storing, in what way does a flat sequence like an array store values of its elements? The author says that the flat sequence physically stores the value of each item. what does he mean by that?

This is my first time asking question. Please excuse my lack of knowledge in this area.

Upvotes: 3

Views: 140

Answers (1)

Ngoc N. Tran
Ngoc N. Tran

Reputation: 1068

Just for the sake of demonstration, imagine int is not a primitive type. Then an array holding the values itself would be like this

Address  0xaddr0  0xaddr1  0xaddr2
        +--------+--------+--------+
Content |   69   |  420   |  1337  |
        +--------+--------+--------+

And lists holding addresses (references) would be like this

Address   0xaddr0   0xaddr1   0xaddr2    0xaddr3   0xaddr4   0xaddr5
        +---------+---------+---------+
Content | 0xaddr3 | 0xaddr4 | 0xaddr5 |    69        420      1337
        +---------+---------+---------+    ^          ^        ^
             |         |         |         |          |        |
             +---------+---------+---------+          |        |
                       |         |                    |        |
                       +---------+--------------------+        |
                                 |                             |
                                 +-----------------------------+

So when you're getting a value from an array, you get it immediately; but for lists, you get the address of that value, then go to that address to actually get the value.

Upvotes: 6

Related Questions