0

I've started to learn to code with Python and I've just come across Loop Lists. They've given two ways to loop and I wondered when and how example A would be better than just using example B (which is more simple imo). When I print to the console they both seem to give me the same result too.

Example A:

myList = ["Apple", "Banana", "Cherry"]
x = 0
while x < len(myList):
    print(myList[x])
    x +=1

Example B:

myList = ["Apple", "Banana", "Cherry"]
for x in myList:
    print(x)
  • The second one is much easier to read, and harder to screw up.. – AboAmmar Jul 06 '22 at 20:14
  • Example B is the prefer way, and in case you need the index you can use the [enumerate](https://docs.python.org/3/library/functions.html#enumerate) function. Here is some related video: [Loop like a native: while, for, iterators, generators](https://www.youtube.com/watch?v=EnSu9hHGq5o) – Copperfield Jul 06 '22 at 20:22

1 Answers1

0

In some situations, you might not want to loop over the entire list - maybe only a part of it, or only upto a certain threshold. In this case, Example A will be able to help you since you can change the 'len(myList)' to whatever value/condition you want to.

Example B is simpler when you want to iterate over the entire list

Yash Laddha
  • 152
  • 7