Is there more pythonic way to get triple sequence

How I can make this more pythonic

def triple_sequence(start, length):
  new_ls = [start]
  while len(new_ls) < length:
    new_ls.append( new_ls[-1] * 3)
  return new_ls
  


print(triple_sequence(2, 4)) # => [2, 6, 18, 54]

print(triple_sequence(4, 5)) # => [4, 12, 36, 108, 324]

Python has a neat feature called “list comprehension”.

thingy = [a+ 3 for a in range(4)]
thingy == [3, 4, 5, 6]

This is no quite what my code does. Each number supposed to be three times the previous one except for first number which is called start.

That’s just an example code for list-comprehension saying “Yes, it can be more pythonic”.
Ofcourse you have to do this yourself :wink:

I could write it, but the idea of the forum is to help people find solutions, not writing it for them.

1 Like

@Jumper You can use a recursive function to do what it is you are trying to do.
I recommend trying find a way to do it with list comprehension as Jagaya suggests.

def triple_sequence(start, length):
    sequence = []
    if length == 0:
        return sequence
    else:
        sequence.append(start)
        start = start * 3
        return sequence + triple_sequence(start, length-1)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.