1

beginner/noob here: If anyone could help explain what is actually happening (behind the code) in simple terms, would be greatly appreciated trying to experiment, why does the second script not output apple?

one = ["apple", "banana", "republic"]

for i in range(len(one)):
    for j in range(i + 1):
        print(one[i])

output

   apple
   banana
   banana
   republic
   republic
   republic

whereas

one = ["apple", "banana", "republic"]

for i in range(len(one)):
    for j in range(i):
        print(one[i])

output doesn't contain apple

   banana
   republic
   republic
1
  • Did you notice the pattern? Your first example prints 1 time, 2 times, 3 times. Your second example prints 0 times, 1 time, 2 times. Commented Apr 30, 2021 at 16:12

3 Answers 3

2

This is quite a fundamental concept in most programming languages: Ranges and indices begin at 0, and exclude the "last" element.

So range(len(one)) will include the numbers 0, 1, and 2.

So then in your second code example, in the first step of the outer loop i will be 0. And then the inner loop would say "Okay, now loop over j starting from 0 and running until, but excluding, 0`. Which means, actually, don't run at all.

You can check this by typing print(list(range(0)) and that should be an empty list.

That's why in your second example the apple doesn't get printed.

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

Comments

0

Thank you all for your help, I understand the reason behind now. I appreciate your time for explaining it to me

Comments

0

The first run of your loop:

for i in range(len(one)):
    for j in range(i):
        print(one[i])

i = 0 => j = 0 to 0: it means that the "j"-cycle condition already done and next iteration of i should be used. And one[i=0] item will not be outputed.

Comments

Your Answer

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