Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...