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
305 views
in Technique[技术] by (71.8m points)

oop - what is implementation or execution Difference Between dictionary with keys as 0,1,2,.. and list in python

li=[1,2]
dic={0:1,1:2}

print(li[0],dic[0])

I have executed following code, they give the same result, is there any implementation or execution or difference in the way the list and dictionary are stored in memory.

it was mentioned on lectures that Dictionary elements are directly accessed, so list takes more time while accessing elements in a huge list compared to a dictionary with keys 0,1,2 with same data as in the list.

Any reasons or confirming hypothesis would be helpful.

Thanks in advance, happy coding

question from:https://stackoverflow.com/questions/65838561/what-is-implementation-or-execution-difference-between-dictionary-with-keys-as-0

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

1 Reply

0 votes
by (71.8m points)

This is false. Both operations are O(1) (constant), and list access will typically be slightly faster:

from timeit import timeit

L = [0 for i in range(10**8)]
D = {i:0 for i in range(10**8)}

%timeit L[9999999]
%timeit D[9999999]

Results:

35.6 ns ± 3.03 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
52.1 ns ± 2.76 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

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

...