0

I have a question ,what is the meaning of "range( i + 1 )" below ,if I want to show the output which has xyyzzz?

a = ("x", "y", "z")
for i in range(len(a)): 
    for j in range( i + 1):
        print(a[i])
output: x
        y
        y                                                                            
        z      
        z   
        z
     
Yeo'
  • 7
  • 2
  • https://stackoverflow.com/questions/50575700/range-function-in-python/50775679 – Vincent Bénet Mar 31 '21 at 11:55
  • 1
    Does this answer your question? [Range function in python](https://stackoverflow.com/questions/50575700/range-function-in-python) – Vincent Bénet Mar 31 '21 at 11:56
  • Does this answer your question? [Why does range(start, end) not include end?](https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end) – Gino Mempin Mar 31 '21 at 12:48

2 Answers2

0

range(n) gives you values from 0 to n-1.

If you are unfamiliar with Python currently, this can be represented in different ways:

In mathematical interval notation, you can represent this as [0,n) . The left value is included, and the right one is excluded.

Taking len(a) to be 3, the above for loops would be written in C as:

for (int i = 0 ; i < 3 ; ++i){
    for (int j = 0 ; j <= i ; ++j){    // note the <= . We can also do j < (i+1)
... 
    }
}

Your code first calculates len(a), which is 3, since this is a container with 3 elements (this specific container is called a tuple). The first for loop goes from 0 to 2, while the second for loop goes from 0 to wherever the counter of the outer for loop is at (less than or equal to). This causes the first value to be printed just once, next twice, and the last one thrice.

(If you want to test your understanding further, try to figure out what would be printed if we had print(a[j]) inside the loops rather than a[i].)

range() is a versatile and powerful thing in Python, it can do much more than just give you values from 0 to n-1. Do read about it if you intend to use Python.

Vishal B
  • 1
  • 1
0

I tried to explain this to you with values

i = 0 ---> j = range(1) = 0 : a[0] = x

--------------------------------
i = 1 ----> j =range(2) = (0,1) : a[1] = y
                                : a[1] = y
 -----------------------------------------   
i = 2 ----> j = range(3) = (0,1,2) : a[2] = z
                                   : a[2] = z
                                   : a[2] = z   
Salio
  • 1,058
  • 10
  • 21
  • but the last instruction, print(a[i]) does not contain j, how can j affect the output ? – Yeo' Apr 01 '21 at 10:20
  • A for loop is used for iterating over a sequence this example j has this role for Understand more read this https://www.w3schools.com/python/python_for_loops.asp – Salio Apr 01 '21 at 13:18