npatel
npatel

Reputation: 1111

How to increment x number of elements repeatedly y times in Python

I have x which is number of elements needed and y which is number of times the elements are needed.

For example:

>>> x = 5
>>> y = 2
>>> for i in range(y):
...  for j in range(x):
...   print j,
... 
0 1 2 3 4 0 1 2 3 4

Expected output is:

0 1 2 3 4
5 6 7 8 9

Can someone help me in achieving the expected output? for loop or list comprehension any way is fine. Thanks in advance.

Upvotes: 0

Views: 276

Answers (5)

SpghttCd
SpghttCd

Reputation: 10860

EDIT: Thanks to @juanpa.arrivillaga this "range-with-offset"-idea became a serious approach in the end:

for i in range(y):
    print(*range(i*x, (i+1)*x))

0 1 2 3 4
5 6 7 8 9

Upvotes: 1

user3483203
user3483203

Reputation: 51165

Option 1

If you need to store the results in a list, you can use unpacking and arithmetic:

>>> [[*range(i*x, i*x+x)] for i in range(y)]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

Option 2

If you're just interested in printing the values, you don't need to waste space by creating the intermediate sublists, and you can instead use the range objects:

for row in [range(i*x, i*x+x) for i in range(y)]:
    print(*row)

0 1 2 3 4
5 6 7 8 9

Upvotes: 4

sacuL
sacuL

Reputation: 51335

It looks like you're just trying to print things, rather than store them (if you want to store them, the other answers look good). You can do it manually with this sort of loop:

for i,v in enumerate(range(y*x)):
    if (i+1)%x == 0:
        print(v)
    else:
        print(v,end=' ')

Output:

0 1 2 3 4
5 6 7 8 9

Edit for python 2: Based on your syntax error in your comment, I suppose you're using python2. Change print(v,end=' ') to print v,:

for i,v in enumerate(range(y*x)):
    if (i+1)%x == 0:
        print v
    else:
        print v,

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95917

You can compose various itertools iterators to create your own generator:

>>> from itertools import count, islice
>>> def foo(x, y):
...     elements = count()
...     for _ in range(y):
...         yield list(islice(elements, x))
...
>>> for es in foo(5, 2):
...     print(*es)
...
0 1 2 3 4
5 6 7 8 9

Upvotes: 1

SpghttCd
SpghttCd

Reputation: 10860

You could use numpy. As you simply count in the range of [0, x*y[ and just want to have it plotted in a certain shape, numpy can exactly do that in a one liner:

import numpy as np
x = 5
y = 2
np.arange(x*y).reshape(y, x)

Result:

array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

Upvotes: 1

Related Questions