Rachel L
Rachel L

Reputation: 53

How do I add a constant integer to a nested list?

I have tried the following code:

list = [[j+i+10 for j in range(1,9)] for i in range (9)]
print (list)

which gives me the output:

[[11, 12, 13, 14, 15, 16, 17, 18], [12, 13, 14, 15, 16, 17, 18, 19], [13, 14, 15, 16, 17, 18, 19, 20], [14, 15, 16, 17, 18, 19, 20, 21], [15, 16, 17, 18, 19, 20, 21, 22], [16, 17, 18, 19, 20, 21, 22, 23], [17, 18, 19, 20, 21, 22, 23, 24], [18, 19, 20, 21, 22, 23, 24, 25], [19, 20, 21, 22, 23, 24, 25, 26]]

However I am looking for an output:

list = [[11, 12, 13, 14, 15, 16, 17, 18],[21, 22, 23, 24, 25, 26, 27, 28],...[91, 92, 93, 94, 95, 96, 97, 98]]

Am i able to do this without the use of any python packages?

Upvotes: 0

Views: 109

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

The "problem" is in used arithmetic function j+i+10. To get desired result, use multiplication instead of addition: j+i*10 (also, the last range should go from 1 instead of 0).

Try:

lst = [[j + i * 10 for j in range(1, 9)] for i in range(1, 10)]
print(lst)

Prints:

[
    [11, 12, 13, 14, 15, 16, 17, 18],
    [21, 22, 23, 24, 25, 26, 27, 28],
    [31, 32, 33, 34, 35, 36, 37, 38],
    [41, 42, 43, 44, 45, 46, 47, 48],
    [51, 52, 53, 54, 55, 56, 57, 58],
    [61, 62, 63, 64, 65, 66, 67, 68],
    [71, 72, 73, 74, 75, 76, 77, 78],
    [81, 82, 83, 84, 85, 86, 87, 88],
    [91, 92, 93, 94, 95, 96, 97, 98],
]

Upvotes: 3

Related Questions