I have been learning different ways of performing the same task as well as perform the same task in the same way just written differently. I can understand the time it takes to execute code that uses different methods can have a different amount of time taken to execute but I do not understand why code that performs the same task in the same method but just written differently can have a total execution time that is not on average the same.
For example.
I can run:
for sub in original_list:
if sub[0] in to_check:
new_list.append(sub)
in a section of my code and my average execution time is around 2.6 ms
However if I change the code to a one liner like this:
new_list = [sub for sub in original_list if sub[0] in to_check]
the execution time is on average 2.4 ms.
As I understand it both do the same operation so this brough up a few questions.
- Where is the change in time coming from?
- Is it scaling? For example if I iterate over a very large list will the time difference grow even bigger or will the time difference stay around 0.10 ms off?
- or am I just very confused and the 2 operations are not as identical as I originally thought?
I am very interested to know if there is a reason for this...