Loops Code challenge: nested loops

Hello all,

I was doing the Loops code challenge. On the 3rd challenge you are asked to write a loop that deletes even numbers from the start of the list and return the list once it comes across an odd number. In return, I wrote the two codes below:

Delete even numbers loop
Delete even numbers 2

I have read the FAQwhich explains some pitfalls of nested loops. Both work if the list argument contains an odd number but if it is all even then the list returns an error. I know it relates to the inner loop running to completion and leaving an empty list which then no longer meets the outer loop condition but cant fully explain it beyond that and I was hoping someone could explain it properly? I have seen the solution which uses an and operator which makes sense! Interestingly, they both return different errors if an all even list which is slightly intriguing since I thought pop(0) and del lst[0] would do the same thing!

Thanks in advance, much appreciated!

If we have a list entirely made out even numbers, the inner loop will delete all the elements (without checking the condition of the outer loop). Which becomes problematic, if the list is empty, then:

lst[0]

is a problem, given there is no element at 0 index, resulting in an error.

you can “visualize” the execution here:

Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution

If you have further questions, please copy paste your code to the forum so we can actual run the code

2 Likes

Ah okay that makes much more sense thanks! I tried writing it out to visualise it but must have made an error somewhere, the python tutor link will be very handy in future!

Apologies, still getting used to the forum, will copy paste it in future!

Thanks again

1 Like