Reputation: 25
list_=[1,3,5,7] for i in list_: for j in range(i): print(i)
output-1,2,2,3,3,3,5,5,5,5,5 .
Upvotes: 1
Views: 38
Reputation: 2585
list_ = [1,3,5,7]
for i in list_:
for j in range(i):
print(i)
What's happening:
for i in list_
), you are iterating over all the four elements in the list_
. It means that the value i
will be 1 in the first iteration, 3 in the second, 5 in the third and 7 in the last.for j in range(i)
) it's created a range of numbers. This time, the for
runs differently and it will no longer get the numbers of the range, but instead repeat i
times the code within it.For example,
for j range(3)
it means, by definition, I'm creating a iterator with length 3 which elements range from 0 to 2:[0,1,2]
which each value will be assigned toj
once.
Since i
in the first outer iteration is 1, so the inner loop firstly will run print(1)
just one time. Then the same will happen with the other remaining numbers from outer loop. Take a look:
for j in range(1)
print(1) # outputs 1
for j in range(3)
print(3) # outputs 3 3 3
for j in range(5)
print(5) # outputs 5 5 5 5 5
for j in range(7)
print(7) # outputs 7 7 7 7 7 7 7
Finally, the correct output should be: 1 3 3 3 5 5 5 5 5 7 7 7 7 7 7 7
Upvotes: 2
Reputation: 51
The output you're providing is wrong. The loop you're doing goes like this: Iterate over provided list and then print out the element of that list (that you're currently iterating over) as many times as the value of the element.
So in your case you'd have: 1, then 3 times 3, 5 times 5 and 7 times 7.
I've simplified your logic here, because for j in range(i) is actually iterating over: 0, 1, 2, ... i (where i equals 1, 3, 5 or 7 depending of the outer loop iteration).
Upvotes: 1