Python : How to limit number of integers printed in a line?

Question:

how would I be able to print say only 10 numbers per line when doing :

for a in range(100 , 201):
    print(a , end=" ")

Doing this would give

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

I would like for it to do this but only list 10 numbers per line so it would be more like

100 101 102 103 104 105 106 107 108 109
110 111 112 113 114 115 116 117 118 119
...
190 191 192 193 194 195 196 197 198 199
200

In total, I would like to achieve this :

Write a program that displays, ten numbers per line, all the numbers from 100 to 200 that are divisible by 5 or 6, but not both. The numbers are separated by exactly one space.

Asked By: Syndux

||

Answers:

You can print out slices.

from itertools import takewhile, count, islice


def slice_iterable(iterable, chunk):
    _it = iter(iterable)
    return takewhile(bool, (tuple(islice(_it, chunk)) for _ in count(0)))


for chunk in slice_iterable(range(100, 201), 10):
    print(*chunk)

Output

100 101 102 103 104 105 106 107 108 109
110 111 112 113 114 115 116 117 118 119
120 121 122 123 124 125 126 127 128 129
130 131 132 133 134 135 136 137 138 139
140 141 142 143 144 145 146 147 148 149
150 151 152 153 154 155 156 157 158 159
160 161 162 163 164 165 166 167 168 169
170 171 172 173 174 175 176 177 178 179
180 181 182 183 184 185 186 187 188 189
190 191 192 193 194 195 196 197 198 199
200

Update Since for whatever reason you don’t like slices, you can do it the counter-way as mentioned in the comments, though I strongly recommend against it, for it is ugly as hell.

counter = 0
for num in range(100, 201):
    counter += 1
    print(num, end=(" " if counter < 10 else "n"))
    if counter == 10:
        counter = 0
Answered By: Eli Korvigo

keep a count of numbers. print an extra print statement if count is multiple of 10

Answered By: arup
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.