1

I am having a problem with my list in python.

I am printing out the list (working), a number that shows the line number (working) and an item in the list that should change every time the list is printed(not working?)

a = ["A", "B", "C", "D", "E"]
b = 0

for x in a:
    while b <= 10:

    print(a, x, b)
    b += 1

My current program output is

['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] A 1
['A', 'B', 'C', 'D', 'E'] A 2
['A', 'B', 'C', 'D', 'E'] A 3

so on

the output I would like

['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] B 1
['A', 'B', 'C', 'D', 'E'] C 2
['A', 'B', 'C', 'D', 'E'] D 3

and so on Although, when I try a different program it works perfectly?

list = ["a", "b", "c"]

for a in list:
    print(a)

Why does this happen and how can I fix it?

5
  • 1
    your for/while loop is not correctly indented. so it is hard to see what's wrong there. Commented Sep 15, 2015 at 7:14
  • I doubt your program outputs what you gave as "current program output". Even after fixing the indentation. Commented Sep 15, 2015 at 7:21
  • @wap26 please expand? Commented Sep 15, 2015 at 7:22
  • @Aymen first your code does not run as is (IndentationError) ; and if I indent either the print or the print and the b +=… in both cases the output is not what you mentioned. Commented Sep 15, 2015 at 7:28
  • @wap26 Sorry that was a formatting error Commented Sep 15, 2015 at 7:40

2 Answers 2

3

That is because you have the while loop inside the outer for loop (that iterates over the elements of the list. So the inner while loop only exists when b becomes greater than 10, and till then the value of x is A.

For what you want I would suggest using itertools.cycle(). Example -

>>> a = ["A", "B", "C", "D", "E"]
>>>
>>> b = 0
>>> import itertools
>>> acycle = itertools.cycle(a)
>>> for i in range(11):
...     print(a,next(acycle),i)
...
['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] B 1
['A', 'B', 'C', 'D', 'E'] C 2
['A', 'B', 'C', 'D', 'E'] D 3
['A', 'B', 'C', 'D', 'E'] E 4
['A', 'B', 'C', 'D', 'E'] A 5
['A', 'B', 'C', 'D', 'E'] B 6
['A', 'B', 'C', 'D', 'E'] C 7
['A', 'B', 'C', 'D', 'E'] D 8
['A', 'B', 'C', 'D', 'E'] E 9
['A', 'B', 'C', 'D', 'E'] A 10
Sign up to request clarification or add additional context in comments.

Comments

2

You have a double loop here (while inside for) and you never reset the b to 0. To get the result you expected, you should use enumerate:

for idx, x in enumerate(a):
    print(a, x, idx)

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.