kashish kashish - 4 months ago 6
Python Question

Rearranging numbers from list in python3

Lets say I have an list of numbers

a = [ 1,2,3,4,5,6,7,8,9,10]

and I want to print the output as

1
2 3
4 5 6
7 8 9 10


How can I do it in python3.

My attempt:

a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(a[i]," ")
i=i+1


I'm getting
IndexError: list index out of range
and also I don't know to print 1 element in 1'st row , 2nd and 3rd in second row and so on.

Answer

One way to do this in Python 3 is to use islice on an iterator :

from itertools import islice

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
it = iter(a)
print('\n'.join([' '.join([str(u)for u in islice(it, i)])for i in range(1,5)]))

output

1
2 3
4 5 6
7 8 9 10