1

I tried to iterate over a list again and again but when the first round is finished I have to print dashes. But the dashes are printing before the round gets fully finished. Here is what I tried so far:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    n = (n+1) % len(lit)
    if lit[n] == lit[-1]:
        print('-'*80)

I also tried the following condition too but it didn't work

if n == len(lit):
    print('-'*80)

here is what I'm getting

1
2
3
4
--------------------------------------------------------------------------------
5
1
.

here is an expected output

1
2
3
4
5
--------------------------------------------------------------------------------
1
.
5
  • 1
    arr is undefined. Commented Aug 6, 2020 at 12:37
  • Shouldn't if n == len(arr): go before you increment n? Commented Aug 6, 2020 at 12:37
  • 2
    If you print the dashes before increasing n, you'll yield the desired output. Alternatively, testing for n == 0 after incrementing would work as well Commented Aug 6, 2020 at 12:38
  • @ScottHunter I'm sorry was typo problem Commented Aug 6, 2020 at 12:38
  • A less wacky approach perhaps? while True: for x in lit: print(x); print dashes; sleep if you really have to Commented Aug 6, 2020 at 12:43

5 Answers 5

4

The proper test would be n == 0.

Sign up to request clarification or add additional context in comments.

Comments

2

Update your n after the print:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    if lit[n] == lit[-1]:
        print('-'*80)
    n = (n+1) % len(lit)

Output:

1
2
3
4
5
----------------

Comments

1

I am not sure if I got the question correctly. Isn't this enough?

from time import sleep as p

lit = [1, 2, 3, 4, 5]
while True:
    for n in lit:
        p(1)
        print(n)
    print('-'*80)

Comments

1

I think this should work for you,

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    n = (n+1) % len(lit)
    if lit[n-1] == lit[-1]:
        print('-'*80)

Comments

0

Make sure you do things in the correct order

First print the number
Then if the number is the last element, print the line
Finally increment the number

Your code but rearranged:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    if lit[n] == lit[-1]:
        print('-'*80)
    n = (n+1) % len(lit)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.