# Optional arguments that affect output

I have a function for finding factors of a number in Python

def factors(n, one=True, itself=False):
def factors_functional():
# factors below sqrt(n)
a = filter(lambda x: n % x == 0,
xrange(2, int(n**0.5)+1))
result = a + map(lambda x: n / x, reversed(a))
return result


factors(28) gives [2, 4, 7, 14]. Now i want this function to also include 1 in the beginning of a list, if one is true, and 28 in the end, if itself is true.

([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else [])


This is "clever" but inelegant.

if one:
result = [1] + result
if itself:
result = result + [n]


This is straight-forward but verbose.

Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function factors can be written differently and still add optional 1 and itself?

-
The straight forward way isn't that verbose. I don't see a different way to do it the doesn't sacrifice readability. – unholysampler Dec 12 '12 at 3:46
You may think it is verbose but it is self explanatory and can easily be commented out without messing around with the core code. – Apprentice Queue Dec 12 '12 at 4:34

[1] * one + result + [n] * itself

I was thinking [1]*int(one) + result + [n]*int(itself), scrolled down and saw this beauty. Didn't know this could be done. +1 – S Prasanth Dec 13 '12 at 5:37