Skip to content Skip to sidebar Skip to footer

How To Print Every Nth Index Of A Python List On A New Line?

I'm trying to print out a list and for every 5 indexes, it prints a new line. So for example, if I have: [1,2,3,4,5,6,7,8,9,10] the output would be: 1 2 3 4 5 6 7 8 9 10 I

Solution 1:

Used a for loop with a step:

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

for i in range(0, len(lst), n_indices):
    print(lst[i:i+n_indices])

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

If you want to be fancier with the formatting you can use argument unpacking like so: print(*list[i:i+n_indices]) and get outputs in this format:

1 2 3 4 5
6 7 8 9 10

Solution 2:

Try this:

a =[1,2,3,4,5,6,7,8,9,10]for i in[a[c:c+5]forcinrange(0,len(a),5)ifc%5==0]:
    print(*i)

the output will be:

1 2 3 4 5
6 7 8 9 10

also you can replace 5 with any other number or variables.

Solution 3:

A bit more idiomatic than the other answers:

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

for group inzip(*[iter(lst)] * n):
    print(*group)

1 2 3 4 5
6 7 8 9 10

For larger lists, it's also much faster:

In [1]: lst =range(1, 10001)

In [2]: n =5In [3]: %%timeit
    ...: forgroupin zip(*[iter(lst)] * n):
    ...:     group
    ...:
236 µs ± 49.7 µs per loop (mean ± std. dev. of7 runs, 1000 loops each)

In [4]: %%timeit
    ...: for i inrange(0, len(lst), n):
    ...:     lst[i:i+n]
    ...:
1.32 ms ± 184 µs per loop (mean ± std. dev. of7 runs, 1000 loops each)

Solution 4:

You can use below code:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i inrange(0, len(a), 5):
    print(" ".join(map(str, a[i:i+5])))

It will give you desired output:

1 2 3 4 5
6 7 8 9 10

Post a Comment for "How To Print Every Nth Index Of A Python List On A New Line?"