Advertisement

Python issues with the For Loop and While Loop

Started by January 28, 2024 09:59 PM
5 comments, last by a light breeze 10 months, 2 weeks ago

I'm now investigating the subtleties of Python loops, specifically the distinctions between for and while loops. However, I've come across several confusing situations that have left me scratching my head. Here are some bits of code that demonstrate my areas of confusion:

Snippet 1:

# Using a for loop to iterate over a list

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:

print(fruit)

Snippet 2:

# Using a while loop to iterate over a list

fruits = ['apple', 'banana', 'cherry']

i = 0

while i < len(fruits):

print(fruits[i])

i += 1

Here are the exact challenges I'm dealing with.

1. Snippet 1's output (using a for loop) appears basic, printing each fruit in the list. However, in Snippet 2 (using a while loop), I'm getting a "IndexError: list index out of range" message. What is generating this problem, and how can I fix it while preserving the while loop structure?

2. While investigating the versatility of these loops, I am unsure of the best strategy for iterating over lists in Python. Are there any advantages or downsides to utilizing for loops instead of while loops when iterating through lists, especially in terms of readability and performance?

3. In terms of termination conditions, and after reviewing, I discovered that while loops require explicit condition changes, whereas for loops handle iterations automatically. How can I verify that my while loop finishes properly without causing an infinite loop or premature termination?

4. Finally, I'd like to understand the instances in which each loop type thrives, particularly in Python programming environments. Could you give real-world instances or use situations where for loops or while loops are better suited for particular tasks?

Your knowledge and views would be beneficial in guiding me through these complications and improving my comprehension of Python loop constructions. Thank you for your support.

I can't reproduce your first problem:

$ cat kk.py
fruits = ['apple', 'banana', 'cherry']

i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1

$ python3 kk.py
apple
banana
cherry
$ 
Advertisement

@sasha_brouse Can you please use the “codebox” for showing your code? It's the box with the “<>” symbol next to the quotes, above the area where you type the message. By doing that, indenting is preserved, which makes it easier to read the code.

  1. The index error happens when you try to select a non-existing value from the list. Eg fruits[100] gives an error since there are less than 101 fruits in you list.
  2. As you can see, the while list has an amount of clutter compared to the for loop. You must create and update an index i, and you need to check whether the end has been reached. As a general rule in Python, prefer for loops if you can.
  3. The while loop indeed needs careful checking whether the loop ends at the right moment. There is no other way. As programmer you must ensure that the end condition will always eventually become False, or your loop is going to take a looong time 🙂 I don't know if you've read about the break statement yet, but that is another way to leave the loop.
  4. For-loops shine when you know in advance how many iterations you must do (although also here the break statement allows bailing out early if you wish to use it). Examples are “all elements in a list or a set”, “all numbers from 1 to 10”, “all letters of the alphabet”, etc. While loops are useful for cases where you don't know the number of iterations in advance. For example “read all lines in a file” (only after reading the entire file you know how many lines it has), or “walk on all tiles to the other end of a path".

While loops are useful for cases where you don't know the number of iterations in advance. For example “read all lines in a file” (only after reading the entire file you know how many lines it has), or “walk on all tiles to the other end of a path".

Maybe not the best example, because reading all lines of a file is in fact very convenient to do with a for loop in Python:

$ cat x.py 
for line in open('x.py'):
    print(line)
$ python3 x.py 
for line in open('x.py'):                                                       
                                                                                
    print(line)
                                                                     

a light breeze said:
Maybe not the best example, because reading all lines of a file is in fact very convenient to do with a for loop in Python:

Yeah, I had that thought as well, unfortunately after I wrote the post.

As for the code, I was under the impression that ypu should read a file with “with”

with open("filename") as handle:
  for line in hamndle:
    print(line)

Reason for that is to ensure the file is closed immediately after leaving the “with” block.

Alberth said:

As for the code, I was under the impression that ypu should read a file with “with”

with open("filename") as handle:
  for line in hamndle:
    print(line)

Reason for that is to ensure the file is closed immediately after leaving the “with” block.

In theory, yes. In practice, the canonical Python implementation uses reference counting to close the file the moment its reference count goes to 0, which is just at the end of the for loop. There's also a garbage collector, but that's only needed for breaking reference cycles. At least that's the way it worked the last time I looked at the Python C API, which was admittedly some time ago.

This topic is closed to new replies.

Advertisement