Open samp-suman opened 2 years ago
line 1:for i in range(1,5): # --> at this point range will give out a value to i
line 2: i=3 # i value getting updated in loop
line 3:print(i)
1st iteration- Execution starts at line 1, i
will get value from the range function.
and as soon as execution gets to line 2, the value of i
gets updated.
so at line 3 it will print as 3.
2nd iteration- After the first iteration execution goes to line 1 and the range function will give the next value to i
, and again coming to line 2 i
will get updated as 3
.
If you are comparing from C for loop, which goes like ->
for(int i=0; i<=4; i++){
//
}
In this way of for loop in C works as updating of value i
and condition checks. This for loop not same like python one.
Below one can be said
C code link-https://onecompiler.com/c/3ynrf4jxd
int a[4] = {1,2,3,4};
int i,j;
j=0;
for(i=a[j];; i=a[j]){
if (j>3)
break;
i=3;
printf("%d", i);
j++;
}
Output:
3333
In Python for loop iteration is done on an iterable object, range()
function generating that iterable object here in your code, so, there is no condition check thing, it's just i
is getting a new value from iterable object every time.
It doesn't matter whether i
gets updated inside the for loop or not, every time execution returns to the start of the for loop, it will get a new value from the iterable object.
@samp-suman The range()
itself can differentiate the loops between Python and C. In Python, there is an advanced concept about iterator
. But what is an iterator
?
An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects like list, tuples, sets, etc. Iterators are implemented using a class and a local variable for iterating is not required here, It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the memory until the item is called specifically which helps us to avoid repeated evaluation. As lazy evaluation is implemented, it requires only 1 memory location to process the value and when we are using a large dataset then, the wastage of RAM space will be reduced the need to load the entire dataset at the same time will not be there.
String, List, Tuple, Dictionary, these datatypes are all iterable objects. Actually, in Python, everything is an object. Those objects of any class that have an iter() method or a getitem() method, are all iterable objects.
For every iterable object have 2 methods/keywords that help to iterate over the iterators. These are -
iter()
keyword is used to create an iterator containing an iterable object.next()
keyword is used to call the next element in the iterable object.For string:
iter_obj = iter("this is a string")
print(iter_obj)
print(next(iter_obj))
print(next(iter_obj))
print(list(iter_obj))
The output of the above code is:
iter_obj = iter("this is a string")
print(iter_obj)
print(next(iter_obj))
print(next(iter_obj))
print(list(iter_obj))
<str_iterator object at 0x7fe786f97b90>
t
h
['i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
For dictionary:
iter_obj = iter({"a": 1, "b": 1})
print(iter_obj)
print(next(iter_obj))
print(next(iter_obj))
print(list(iter_obj))
print(next(iter_obj))
The output of the above code:
<dict_keyiterator object at 0x7fe786fa6e30>
a
b
[]
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
[<ipython-input-25-16e18c3bd622>](https://localhost:8080/#) in <module>
4 print(next(iter_obj))
5 print(list(iter_obj))
----> 6 print(next(iter_obj))
StopIteration:
If you see the outputs, you can see some differences. As there are only 2 keys to the dictionary, that's why after executing the 4 lines, there is nothing left for further iteration. That's why we got an empty list as output for the 5th line. And if you want to do the next() operation will get the StopIteration Error
which is logical. These internal things happen to every iterable object in Python.
It's getting interesting to the numbers/integers. As Integers do not have iter() or getitem() method, integers are not iterable. You can verify this by using the below code.
iter_obj = iter(7)
The output of the above line is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
[<ipython-input-26-9c1c9aac4342>](https://localhost:8080/#) in <module>
----> 1 iter_obj = iter(7)
TypeError: 'int' object is not iterable
If you have done some python code then you are much familiar with this error. You will get the same error if you execute the below code.
for i in 4:
print(i)
So I guess till now you have understood what is Iterator
is in Python. And you might have guessed what the range()
method does internally. The range()
method will return an iterable object from 0 to the number 4 if you use range(4)
. And the for
loop simply calls the next()
method repeatedly until nothing left to iterate. This happens all time with Python for
loop. But there is nothing like this complexity in C programming. That's why though you are changing the value of i
in the loop, it not change the loop conditions as well.
Hope this will give you a better understanding.
Output:
Question is:-
3
printed four times even when I put the value ofi
as 3 inside the loop. So it should have been an infinite number of 3s in output isn't it? It seems like loop variablei
is different fromi
variable inside the loop.Python for loop seems to be quite different from say, for loop in C?