I come across this code while looking for a way to measure functions speed.
def test():
"""Stupid test function"""
L = []
for i in range(100):
L.append(i)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
when I run it, it takes about 10 seconds, which is very strange for me. I recall that when I am appending 100.000 string into a string, it only takes 0.06 seconds. why does appending 100 integers into a list take 10 seconds? here are the code that I use to append stringt to list.
def wordlist1():
fin = open("words.txt")
word_list = []
for line in fin:
word = line.strip()
word_list.append(word)
return word_list
range()for your integers, which might be slower thanfor line in fintestwith another function the same apart romL.append('a')- you're comparing 2 completely different thingsrangein Python 3 doesn't create a list of integers in memory; it's arangeobject with a__next__method just like a file iterator.