pythonlist-comprehension

Create list of factorials using list comprehension


I'm trying to build a list of the first ten factorials

[1,1,2,6,24,120,720,5040,40320,362880]

using only list comprehension. Is that possible?

I don't know generators or lambda.

Here's my attempt, but I absolutely know why it's wrong:

lst = [1] + [i for i in range(1,10)]
lst[1:10] = [lst[i-1] * i for i in range(1,10)]
print(lst)

Solution

  • Just for fun:

    One-liner mega-hack using list comprehension and an auxiliary accumulator (the resulting list itself) to reuse previously computed value

    s=[1];  s=[s[-1] for x in range(1,10) if not s.append(x*s[-1])]
    

    result:

    [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
    

    note: The math.factorial answer is the way when elements are random. Here it's faster because we can reuse previous results.

    There's also another drawback: the need to store all elements in a list because python does not allow if and assignment like C does. So we have to append to a list and negate the None it returns so if test is True

    As I said: fun, but still a hack.