Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store len(list) somewhere?

Tags:

python

code1:

list=[1,2,3,4,5]
for i in range(len(list)):
    for j in range(len(list)):
        print(i+j)

code2:

list=[1,2,3,4,5]
l=len(list)
for i in range(l):
    for j in range(l):
        print(i+j)

Dose code2 faster than code1?

like image 849
bytefish Avatar asked Dec 10 '22 09:12

bytefish


1 Answers

There will be no noticeable difference. len(somelist) is a very fast O(1) operation. Lists have their length stored internally, so there's very little work to be done when you ask a list for its length.

like image 96
timgeb Avatar answered Dec 21 '22 00:12

timgeb