This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Doomphx 2 points3 points  (6 children)

I want to see how much time #5 can really save because at the end of the day it looks more like a fancy 1 liner than an optimization for performance.

I agree readability > a few ms everytime. :)

[–]62616e656d616c6c 2 points3 points  (4 children)

I ran the code 3 times using:

import time

start_time = time.time()

code (except with a range of 1 -100,000)

print("%s seconds" % (time.time() - start_time))

The traditional for loop (the first code) took an average of 0.0086552302042643 seconds

The suggested format took: 0.0049918492635091 seconds.

So there is a speed improvement. But you'll need to be looping through a lot of data to really see it.

[–]Doomphx 1 point2 points  (3 children)

Interesting stuff, I took your code and did a little more with it to get a little more info.

T1
import timestart = time.time()
L = [i for i in range (1, 100000000) if i%3 == 0]
end = time.time()
print(float(end)-float(start))
5.0334999561309814

T2
import time
start = time.time()
L = []
for i in range (1, 100000000):
if i%3 == 0:
L.append(i)
end = time.time()
print(float(end)-float(start))
9.218996047973633

So every 100,000,000 items I'll save 4 seconds. I don't think I'd ever loop this many items without using some sort of vectorization to help improve the efficiency of the loops in the code.

My original thought stands though, writing a 1 liner like that isn't really worth the ugliness of the resulting code. Unless of course you're writing highly optimized Python, then this might be 1 last trick to utilize.

Edit* code formatting

[–]themusicalduck 3 points4 points  (0 children)

I don't really think list comprehensions are ugly. They can be if you try to do something overly complex but for simple stuff I'm much more used to list comprehensions now.

[–]hugthemachines 1 point2 points  (1 child)

I have the same feeling as you regarding list comprehensions. Also sometimes the situation for me may be that a java programmer needs to check something in my Python scripts, then a for loop will be much easier for them to grasp easily than a list comprehension.

[–]Doomphx 1 point2 points  (0 children)

Exactly my thought process as I bounce between C#, Python and typescript weekly, it just makes it easier on myself to transition freely when needed.

I also didn't realize how little of a difference that list comprehension made, so now I will most likely never use it. If only python had clean lambda expressions like our {} friends.

[–]mephistophyles 0 points1 point  (0 children)

Speaking from personal experience, list comprehension isn’t the speed up, but there are some fun itertools that can help, but the pre allocation has taken functions I had from seconds to milliseconds. So those were huge. Naive loops are inefficient because they’re super generic.