0

I am fairly new to array data structures. I am trying to print the below pattern in python.

12345
1234
123
12
1

Here is my code:

a = [1,2,3,4,5]
n = len(a)
for i in range(n, 0, -1):
    for j in range(i):
        print a[j],

Output: I am getting the correct order. I just can't seem to arrange the answer in the desired format. Any suggestions?

1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
suyash gautam
  • 169
  • 1
  • 2
  • 9

1 Answers1

1

If you're really just interested in learning about list manipulations, and don't need exactly the output you've shown, you might consider this approach, which makes use of basic list indexing:

for i in range(n, 0, -1):
    print(a[:i])

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]

Along those lines, you can get your specified output by converting the values in each row to type str, joining each row's characters, and then printing:

for i in range(n, 0, -1):
    print(''.join(str(el) for el in a[:i]))

Output:

12345
1234
123
12
1
andrew_reece
  • 20,390
  • 3
  • 33
  • 58