# Triangled printing

This code prints numbers in a triangled way, such as:

1
12
123
12
1


This is the code:

def triangled(num):
num = str(num)
pieces = [num[:i] for i in range(len(num))]
return pieces + [num] + pieces[::-1]

def triangled_print(num):
for i in triangled(num):
print(i)

triangled_print(123456789)


The code looks fine.

I have a few suggestions, but these are nitpicks rather than major problems:

• Give your functions better names. I'd suggest triangle_lines and triangle_print, because triangled is just a bit ambiguous. Along the same lines, consider adding docstrings so that the user can more easily find out how your code works.

• In the final line of triangled, I'd write it slightly differently:

return pieces + [num] + list(reversed(pieces))


There's nothing wrong with taking a reverse slice, but I think this makes it slightly clearer what's going on.

• If you used this code on a really long number, you might start to have memory problems with the list returned from triangled(<bignum>). You could rewrite it to be a generator, but it's not essential if you're only going to be using this for small numbers.

• Your triangle has a blank line at the top or bottom. That might be okay; if not, tweak the range to start at 1 instead of (implicit) 0:

pieces = [num[:i] for i in range(1, len(num))]