Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting values to lists using list comprehensions instead of list() #114

Open
AN3223 opened this issue May 30, 2018 · 7 comments
Open

Comments

@AN3223
Copy link

AN3223 commented May 30, 2018

Recently I've been using a lot of list comprehensions in Python. They're really useful. But I noticed that a lot of the time when I wanted to convert a generator or something into a list, I'd quickly write something like [x for x in whatever] and nothing else, when just list(whatever) would suffice. I suppose it's a readability thing?

So in short:

Anti-pattern

xs = (1, 2, 3, 4)
ys = [x for x in xs]

Best practice

xs = (1, 2, 3, 4)
ys = list(xs)
@adewes
Copy link
Member

adewes commented Jun 4, 2018

Sounds great, can you write a draft for this (have a look at a rst file to see how the anti-patterns are structured)?

@AN3223
Copy link
Author

AN3223 commented Jul 16, 2018

For sure, here's a draft of it: https://gist.github.com/AN3223/344d27279be6ee87e13c5fadf1af756d

Apologies for the procrastination!

@dejanbatanjac
Copy link
Contributor

dejanbatanjac commented Jun 1, 2019

The best for this example would be to use:

xs=(1, 2, 3, 4)
xs=[*xs]
xs # [1,2,3,4]

as [] is faster than list()

@tucked
Copy link

tucked commented Jun 1, 2019

I'm not sure about that:

$ python3 -m timeit -n 1000 -s 'x = range(1000000)' -- 'list(x)'
1000 loops, best of 5: 68.1 msec per loop
$ python3 -m timeit -n 1000 -s 'x = range(1000000)' -- '[*x]'
1000 loops, best of 5: 68.3 msec per loop

FWIW, I would probably consider list() more readable anyways.

@dejanbatanjac
Copy link
Contributor

@tucked, let it got with the list(), my tip was based on https://stackoverflow.com/questions/30216000/why-is-faster-than-list analysis.

@tucked
Copy link

tucked commented Jun 3, 2019

Yes, but I suspect after a certain point, as in my example, overhead is essentially negligible compared iteration over x. Even at small scale, I would not consider the performance boost significant enough to warrant the sacrifice of readability:

$ python3 -m timeit -n 1000000 -s 'x = range(1000)' -- '[*x]'
1000000 loops, best of 5: 44.7 usec per loop
$ python3 -m timeit -n 1000000 -s 'x = range(1000)' -- 'list(x)'
1000000 loops, best of 5: 57.2 usec per loop

I would call this premature optimization, but, you know, that's just, like, my opinion, man.

@dejanbatanjac
Copy link
Contributor

@tucked, using list() is just fine. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants