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

big o - Python: List creation by multiplication operator time complexity

Python What's the time complexity of using

a = [1]*n 

vs.

for i in range(n): 
    a.append(1)

Are both O(n) or does the first O(1)?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The former is O(n), due to the use of PyList_New() with a known size. The latter is slightly worse than O(n), due to the need to resize the list after several appends.


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

...