Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

python - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...