+ 1
Can anyone pls explain me the concept for i in range with an example its becoming confusing in further modules
4 Antworten
+ 4
for I in range() in python... the I is the 'loop number' as u may put it. say you have an array and u wanted to print everything. for every loop it increments by one. i=1 then 2 then 3 for every loop
+ 3
for example
for i in range(11):
print (i)
would print 0 through 10
+ 3
If you want to understand it properly, read up on iterators, iterables and range objects in the python documentation.
For now and until you completed the course just know the following:
range(n) contains all numbers 0, 1, 2, ... , n-1
If n is 5, this will be 0,1,2,3,4
range(m,n) contains numbers m, m+1, ... , n-1
range (2,6) contains 2,3,4,5
range(m,n,s) will contain m, m+s, m+2s, ... as long as that number is smaller than n
range (2,10,2) contains 2,4,6,8
for goes over the elements in the range. In the first iteration of
for i in range (2,8):
#something
i will be 2, then 3 and so on...
0
for i in range(10)
i is a variable. it could be named anything. for Aryan in range().. when the for loop runs, it runs a set amount of times. in the case of range(), it runs the number of times you give it. for i in range(10) will run 10 times. each time it runs, i becomes the number it is on. it's first run, the variable i is 1. next run the variable i is 2. that is why
for i in range(10):
print(i)
will print the numbers 1 then 2 then 3 then 4 ..Etc.
so if you had a list and ran across it in range..
myList=["hi","bye"]
for i in range(5):
print(myList[i]) <--i in range is a number, so we can use it as a list index that will increase by 1 each time, cycling thru the list.
this results in
[bye]
Error
because first range is 1 we get index 1. second range is 2, but index 2 doesn't exist. but what if we wanted to print the list, how would we do that?
well, if we know the size of the list beforehand and start from 0..
for i in range(2):
print(myList[i-1]) <<i on first run is 1. we subtract 1 from each i range to move it back 1 to account for 0 index. the output here is
[hi,bye]
what if we didn't know how long the list was and wanted to print it anyway? well, range isn't the only thing we can use to set the length of our loop. we can use the actual length of something
for i in range(len(myList)):
that returns a range of 2 as our list has a length of 2 .. But the easiest way to for loop thru a list is to avoid range all together. you want to loop thru a list? then just loop thru the list.
for i in myList:
print(i)
since the loop isn't looping a numbered range, i != a number. I becomes each item in the list. the output of this loop is
hi
bye