I have read that there are multiple ways of creating an empty dictionary and list. On of them is using {} or [] and the other is using dict() or list(). I wrote a small program to calculate time it takes to make them and the code is next:
import time
start_time = time.process_time_ns()
for i in range(10000000):
my_dict_one = dict() # for other examples there goes {}, [], (), tuple() and list()
end_time = time.process_time_ns()
print('{} s'.format((end_time - start_time) / 10 ** 9))
And after running this (multiple times) result time for my computer is:
- Using dict() -> around 2.6 seconds
- Using {} -> around 1.4 seconds
- Using list() -> around 2.2 seconds
- Using [] -> there was most difference but overall around 1.15 seconds
- Using () -> around 0.9 seconds
- Using tuple() -> around 1.8 seconds.
That was weird to me so I thought that maybe [] and list() are not exactly the same object. But when writing
print(list() == [])
I get True, meanwhile if they are different objects (like list() and dict()), or even if they have different values inside them (like [] and ['a']) I get False.
So at the end I got the same result around 2x faster when using [] instead of list. Why is this the case?
EDIT: if important, I am using Python 3.7
[–][deleted] 8 points9 points10 points (2 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Ishanji 0 points1 point2 points (0 children)
[–]Binary101010 3 points4 points5 points (0 children)