0
How can I use while loop to iterate through lists or strings if I don't want to use the for in loop in python?
While
3 Respostas
+ 4
For example :
a = [i for i in range(11)] # this can be done also putting the numbers one to one
j = 0
while j < len(a):
i = a[j]
print(i)
j+=1
In this situation the while loop is evaluating the j variable to not be same as length of a.
So j represents the index of elements of a.
Before the increment of j, you can operate as you want with values of a thanks to i.
So it is possible to use while instead of for but for iterate directly in a list, rather getting them with index.
But try more with the for loop if you have a finite collection of values, and while for infinite ones or those which you don't know the limit 😀.
The Zen of Python :
"Simple is better than complex ... Complex is better than complicated."
+ 2
It depends what you need in task and write some condition after while
+ 1
Abdulmuiz Adeyemo why "don't [you] want to use the for loop in python"?
if that's because you find it too much hard to do, don't expect to feel easier to use 'while' loop ^^
appart for specific and few cases, a 'for' loop is often the easiest and shorter (at least in Python) way to iterate ;P