Home > other >  How to generate even numbers with a length limit?
How to generate even numbers with a length limit?

Time:03-07

I want to generate a list of even but want to specific how many numbers to be added to the result too.

start, n = 2, 5

def fEven(start, n):
    #do something
fEven(start, n)

This should generate 2,4,6,8,10 as 5 was specified for the total number to be generated

CodePudding user response:

Classic loop way:

def fEven(start, n):
    res = []
    for i in range(n):
        res.append(start)
        start  = 2
    return res

Or shorter:

def fEven(start, n):
    return [start   (i*2) for i in range(0,n)]

CodePudding user response:

You can use this way to solve the problem.

def fEven(start, n):
    return list(range(start,start   2 * n, 2))
  • Related