BigBoyProgrammer
BigBoyProgrammer

Reputation: 59

How come 1 is printed instead of 0?

I am confused as to why '0' is never printed when I print the value for 'i'. Why is this.

Thanks in advance for your help.

for i in range(0,10):
  for z in range(i):
    print([i], end=' ')

Upvotes: 0

Views: 790

Answers (4)

t.m.adam
t.m.adam

Reputation: 15376

if you modify your code like this :

for i in range(0, 10): 
    for z in range(0, i):
        print([z], end=' ')
    print('')

It prints :

[0]
[0] [1]
[0] [1] [2]
[0] [1] [2] [3]
[0] [1] [2] [3] [4]
[0] [1] [2] [3] [4] [5]
[0] [1] [2] [3] [4] [5] [6]
[0] [1] [2] [3] [4] [5] [6] [7]
[0] [1] [2] [3] [4] [5] [6] [7] [8]

Upvotes: 1

Deba
Deba

Reputation: 609

because range(0) will give [], so it is not printing

Upvotes: 0

rmeertens
rmeertens

Reputation: 4451

The range function in python yields/gives values up to (but not including) its argument. So list(range(5)) will be [0,1,2,3,4], and list(range(0)) will be... []

As you want to print i for each value in this empty list, you don't print i at all!

Hope this helps, and let me know if I did not explain it clear enough!

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160447

Because range(0) has nothing for you to iterate through so you just don't iterate in that case:

for i in range(0): print(i)

prints nothing because it's like doing:

for i in []: print(i)

and you'd be able to see this with a little experimenting:

>>> list(range(0))
[]

Upvotes: 2

Related Questions