1
x= (i for i in range(3))
print(x)
for j in x:
    print(j)
    for i in x:
        print(i)

O/P: 0 1 2

please explain the code i am not able to wrap my head around this code

i expected this code to print 0 1 2 0 1 2 but the solution is 0 1 2

2 Answers2

2

x is not a tuple. x is a generator. After you have printed x, you have consumed everything from the generator, so it is positioned at the end, and there's nothing left for the for statements. If you need to reuse the data, convert it to a tuple:

x = tuple(i for i in range(3))

or even

x = tuple(range(3))
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
2

x is a generator. If you want to get 0 1 2 0 1 2 you can use:

x= [i for i in range(3)]  # or x = list(range(3))
for i in range(2):
    for num in x:
        print(num)

or use the range function without creating a list:

for i in range(2):
    for num in range(3):
        print(num)

Note: if you create this code

for num1 in range(3):
   print(num1)
    for num2 in range(3):
        print(num2)

The output will be 0 0 1 2 1 0 1 2 2 0 1 2 and not 0 1 2 0 1 2...

Chana Drori
  • 159
  • 1
  • 1
  • 10