Cyclic outputs using list comprehensions and modulo

Question:

I am trying to get this output using list comprehensions and modulo:

0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678

My current code is:

lst = [i for i in range(10)]

for j in range(len(lst) - 1), lst:
    for i in range(1):
        lst.append(lst.pop(0))
        print(*lst)

How can I improve this code using modulo? Maybe even optimise it in 1 line?

Asked By: iwannabeadog

||

Answers:

I think you may be over-complicating this somewhat – this would seem to have the intended result – using string.join. Note that we convert the members of the list to strings to enable us to use this approach.

Code:

lst = [str(i) for i in range(10)]

for i in range(len(lst)):
    print(''.join(lst))
    lst.append(lst.pop(0))

Output:

0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678

Alternatively – if you want the result in one string:

>>> print(''.join([v for x in [lst[i:] + lst[:i] + ['n'] for i in range(len(lst))] for v in x]))
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
Answered By: CDJB

Fun fact that you can also do this with deque – and it will allow you to go either direction, in any increment.

from collections import deque
dq = deque([i for i in range(10)])

for x in range(len(dq)):
    ''.join(map(str,dq))
    dq.rotate(-1)

Output

'0123456789'
'1234567890'
'2345678901'
'3456789012'
'4567890123'
'5678901234'
'6789012345'
'7890123456'
'8901234567'
'9012345678'
Answered By: Chris

Edit: I think I get your question, here is a solution with %:

n = 10 # You can take any number, the list will be a cycle of numbers from 0 to 9
lst = [i % 10 for i in range(n)]

for j in range(len(lst)):
    print(''.join([str(k) for k in lst]))
    lst = [(i + 1) % 10 for i in lst]

My previous answer:

An absolutely ugly one with itertools.cycle()

import itertools

lst = [str(i) for i in range(10)]
cpt, turn = 0, 0

for char in itertools.cycle(lst):
    if turn >= len(lst):
        break
    if cpt >= len(lst):
        cpt = 0
        turn += 1
        print()
    else:
        print(char, end='')
        cpt += 1
Answered By: Andy