Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print numbers 5x5 with nested list

Is there a way to write the code below in an easier way? The code:

lista = []

for i in range(5):
    lista.append([])    # >>> [[], [], [], [], []]

l25 = []
for i in range(1, 26):
    l25.append(str(i).zfill(2))

part = 5
k = 0
while k < len(lista):
    lista[k] = l25[part-5:part]
    k = k + 1
    part = part + 5

i = 0
while i < len(lista):
    print(*lista[i], sep="  ")
    i = i + 1

I want to use a nested list with several lists into.

The code above will print:

01  02  03  04  05
06  07  08  09  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
like image 638
K Doe Avatar asked Dec 18 '25 08:12

K Doe


2 Answers

You can build your grid with a list comprehension and then print it:

grid = [[str(i).zfill(2) for i in range(j, j + 5)] for j in range(1, 26, 5)]

for line in grid:
    print('  '.join(line))

Output

01  02  03  04  05
06  07  08  09  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
like image 68
slider Avatar answered Dec 19 '25 20:12

slider


You could use itertools.count:

from itertools import count

counter = count(1)

lista = [[str(next(counter)).zfill(2) for j in range(5)] for i in range(5)]

i = 0
while i < len(lista):
    print(*lista[i], sep="  ")
    i = i + 1

Output

01  02  03  04  05
06  07  08  09  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
like image 42
Dani Mesejo Avatar answered Dec 19 '25 22:12

Dani Mesejo