fork download
  1. import random
  2. import time
  3.  
  4. TIMES = 1000
  5.  
  6. def add_remove_tuple(x):
  7. el = random.randint(0,len(x)-1)
  8. idx = x.index(el)
  9. x = x[:idx] + x[idx+1:]
  10. x = x + (el,)
  11.  
  12. def add_remove_list(x):
  13. el = random.randint(0,len(x)-1)
  14. x.remove(el)
  15. #idx = x.index(el)
  16. #x.pop(idx)
  17. x.append(el)
  18.  
  19. def time_tuple():
  20. x = tuple(i for i in range(20000))
  21. t = time.time()
  22. for i in range(TIMES):
  23. add_remove_tuple(x)
  24. return time.time() - t
  25.  
  26. def time_list():
  27. x = [i for i in range(20000)]
  28. t = time.time()
  29. for i in range(TIMES):
  30. add_remove_list(x)
  31. return time.time() - t
  32.  
  33. print("%d repetitions of add/remove at random position using tuple: %.3f seconds" % (
  34. TIMES, time_tuple()))
  35.  
  36. print("%d repetitions of add/remove at random position using list: %.3f seconds" % (
  37. TIMES, time_tuple()))
Success #stdin #stdout 1.28s 12448KB
stdin
Standard input is empty
stdout
1000 repetitions of add/remove at random position using tuple: 0.624 seconds
1000 repetitions of add/remove at random position using list: 0.622 seconds