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)
2
  • The second one is much easier to read, and harder to screw up.. Commented Jul 6, 2022 at 20:14
  • Example B is the prefer way, and in case you need the index you can use the enumerate function. Here is some related video: Loop like a native: while, for, iterators, generators Commented Jul 6, 2022 at 20:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.