Jofumi
Jofumi

Reputation: 85

How to properly combine function and list generator?

As I know list generators are a little bit quicker than using .append(). So I was just interested how could I implement this code, but using the generator. All that matters is that I need to get list in the end.

this is the original script:

x=4
def factorial(n):
    f=1
    list = []
    for n in range(1, n+1):
        f = f * n
        list.append(f)
    return list
testList = factorial (x)
for i in range(x): print(testList[i], end = ' ')

I've tried this:

f=1
n=4
def fun(n):
    f=f*n
    return f
testList = [fun(f) for n in range(1, n+1)]

and this is definitely not the way to do it (the program says that in function f is not declared. and overall... just tried this to test) also tried this:

testList = [lambda f : f*n for n in range(1, n+1)]

but all I got this way is the list of functions. I could get the factorial still, but not the way it should be.

This is a little bit problematic for me because there is a buffer variable (f in the original script).

Upvotes: 2

Views: 96

Answers (3)

GZ0
GZ0

Reputation: 4273

In the upcoming Python 3.8 scheduled to be released next month, the new assignment operator := makes it possible to generate the sequence using a list comprehension:

p = 1
output = [(p := p * i) for i in range(1, n + 1)]

Upvotes: 3

Rob Streeting
Rob Streeting

Reputation: 1735

You're first example is nearly there, you just need to make two tweaks:

  • You need to pass in n rather than f to fun.
  • You need to use global to make sure that the f you refer to in the function is the f declared outside of the function. Otherwise, f will not be updated on each iteration of the list generator.
    f=1
    n=4
    def fun(n):
        global f
        f=f*n
        return f
    testList = [fun(n) for n in range(1, n+1)]

Upvotes: 1

sanyassh
sanyassh

Reputation: 8530

You can implement it in this way, with usage of global keyword:

f = 1
n = 4

def fun(n):
    global f
    f = f * n
    return f

testList = [fun(n) for n in range(1, 10+1)]
print(testList)

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

Upvotes: 3

Related Questions