+ 2

difference in while loop

Is there a difference in these two codes: x = int(input()) i = 0 while i < x: print(i) i+=1 vs: x = int(input()) i = 0 while i in range(x): print(i) i+=1 They both output the exact same thing but was wondering, is there a difference?

4th Dec 2022, 2:40 AM
Yusuf C
8 Réponses
+ 5
the code for the speed test and my comments are all in the attached file: https://code.sololearn.com/c7933FqE2tJv/?ref=app
4th Dec 2022, 9:28 PM
Lothar
Lothar - avatar
+ 4
intresting. Thank you so much everyone!
5th Dec 2022, 12:12 AM
Yusuf C
+ 3
Oma Falk , good idea to make a speed comparison. i will come back with this.
4th Dec 2022, 1:23 PM
Lothar
Lothar - avatar
+ 3
SoloProg Yes, there is no comparison while there is one for if i< n and some more for if i in range(n).
4th Dec 2022, 4:13 PM
Oma Falk
Oma Falk - avatar
+ 3
The difference is that the predefined library is usually faster than loops. But we can get the same outputs
5th Dec 2022, 3:07 AM
Aina Temiloluwa
Aina Temiloluwa - avatar
+ 2
First one might have a better performance
4th Dec 2022, 5:46 AM
Oma Falk
Oma Falk - avatar
+ 2
Lothar I remember you are a specialist for it. I am curious about the result.
4th Dec 2022, 1:41 PM
Oma Falk
Oma Falk - avatar
+ 2
The test turned out that the for loop was the fastest. https://code.sololearn.com/cGiG8PC24Hft
4th Dec 2022, 4:03 PM
SoloProg
SoloProg - avatar