7 posts were split to a new topic: How does this code loop I wrote work?
4 posts were split to a new topic: Why does my loop skip indexes of my list?
2 posts were merged into an existing topic: Why is len(lst) > 0 necessary for solving the list challenge?
4 posts were split to a new topic: Why doesn’t my code work how I expected?
15 posts were split to a new topic: Question on loops
5 posts were split to a new topic: Can you help me convert this into list comprehension?
3 posts were split to a new topic: Why do I get ‘None’?
2 posts were split to a new topic: I don’t know what my code does?
4 posts were merged into an existing topic: Why doesn’t iterating with
for work while removing items from a list?
4 posts were merged into an existing topic: Why is len(lst) > 0 necessary for solving the list challenge?
for i in lst:
this is solution with for loop, help to understand why it didnt work before with your for loops.
I was wondering why we can’t use the continue for this problem, I tried it and it seems to be wrong but I don’t know why.
for num in lst:
if num % 2 == 0:
Since you’re asked to create a list you’ll want to use list operations like append or something else to manipulate the elements, you’re doing none of that. It also says starting evens, not all even, so you’re ignoring half the condition. Consider how you’d do it manually, what steps does that involve?
What do you think
What is wrong with this code?
def delete_starting_evens(lst): while lst%2 == 0 and len(lst)>0: del lst return lst
I’m checking if both exercise conditions are true, then deleting first element of the list, thus making the list shift positions so if both conditions are still met “while” loop will do it’s thing again and then if one of conditions if not met list is getting returned.
But I’m getting following error:
File “script.py”, line 10, in
print(delete_starting_evens([4, 8, 10]))
File “script.py”, line 3, in delete_starting_evens
while lst%2 == 0 and len(lst)>0:
IndexError: list index out of range
The comparison operations take place from left to right. The safeguard of the first comparison happens to be the second, which is an odd order to stack things up. Perhaps if they were switched?
Switching places did work (thanks a lot!) but I don’t know what do you mean by that sentence.
Examine the error message.
What triggered it?
>>> a =  >>> a = 1 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> a = 1 IndexError: list assignment index out of range >>>
Testing the length first short circuits the AND logical expression. The second (accessing) operand is never evaluated.
Is it because in the case of the empty list modulo operand is trying to divide a 0 (empty list) by 2?
It never makes it that far. Python is being told to access a non-existent element. It refutes that order by delivering an exception notification.
while lst % 2 == 0 ^ | accessor