In Python, I really enjoy how concise an implementation can be when using list comprehension. I love to do concise list comprehensions this:
myList = [1, 5, 11, 20, 30, 35] #input data
bigNumbers = [x for x in myList if x > 10]
However, I often encounter more verbose implementations like this:
myList = [1, 5, 11, 20, 30, 35] #input data
bigNumbers = []
for i in xrange(0, len(myList)):
if myList[i] > 10:
bigNumbers.append(myList[i])
When a for loop
only looks through one data structure (e.g. myList[]
), there is usually a straightforward list comprehension statement that is equivalent to the loop.
With this in mind, is there a refactoring tool that converts verbose Python loops into concise list comprehension statements?
Previous StackOverflow questions have asked for advice on transforming loops into list comprehension. But, I have yet to find a question about automatically converting loops into list comprehension expressions.
Motivation: There are numerous ways to answer the question "what does it mean for code to be clean?" Personally, I find that making code concise and getting rid of some of the fluff tends to make code cleaner and more readable. Naturally there's a line in the sand between "concise code" and "incomprehensible one-liners." Still, I often find it satisfying to write and work with concise code.
xrange(0, len(myList))
withenumerate(myList)
? This would be especially useful when trying to clean up someone else's code, or trying to convert some messy code into something that's usable in a tutorial. – Lythraceousfor elem in myList:
. – ForgottenWhat is Pythonic? "for i in range(len(seq)):"? No. Use "for obj in seq:".
– Keleurllib
to post a question on SO, wait 2-3 minutes and then download the answer. – Pyroelectric