Python collecting outputs into a list?

115 Views Asked by At

Instead of printing the numbers in the sequence it should collect them in a list and return the list. Here is the code that prints numbers in the sequence:

def collatz_sequence(n):
    while n > 1:
        print(n)
        if n % 2 == 1:
            n = 3*n + 1
        else:
            n = n // 2
1

There are 1 best solutions below

0
On

Use list.append:

def collatz_sequence(n):
    lst = []
    while n > 1:
        lst.append(n)
        if n % 2 == 1:
            n = 3 * n + 1
        else:
            n = n // 2
    return lst

Here is a note:

Since n is an integer, n % 2 can only equal to 1 or 0, hence

if n % 2 == 1:

can be simplified to

if n % 2: