| tags: [ programming Python ] categories: [Development ]
Python List Comprehensions limit results
List comprehensions make working in python much more engaging. I am finding that they can cut down on lines of code while still conveying meaning. Most recent example is a case where I wanted to add a parameter to a function to limit rows returned if it was set to a positive number.
For example:
def generateResults(x,y,limit=-1):
return [v for i,v in enumerate(permutations(x,y)) if limit < 0 or i < limit]
The permutations call a suitable replacement of more detailed server query code. Some example runs to demonstrate how limit and enumerate work here.
>>> generateResults("ABC",3)
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
>>> generateResults("ABC",3,limit=1)
[('A', 'B', 'C')]
>>> generateResults("ABC",3,limit=3)
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C')]
This was very helpful when to limit the results from an operation that would otherwise take too long.