Hi, I am currently solving a little question on loops from Codecademy projects, question is as follows:
make a function for Deleting Starting Even Numbers
Let’s try a tricky challenge involving removing elements from a list. This function will repeatedly remove the first element of a list until it finds an odd number or runs out of elements. It will accept a list of numbers as an input parameter and return the modified list where any even numbers at the beginning of the list are removed.
So, here’s my solution:
def delete_starting_evens(lst):
for num in lst:
if lst[0] % 2 == 0:
lst = lst[1:]
return lst
here I used for loop, but as per Codecademy solution the code is with while loop as follows:
def delete_starting_evens(lst):
while (len(lst) > 0 and lst[0] % 2 == 0):
lst = lst[1:]
return lst
And some examples to try this function are:
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))
which will give output same as per both codes, for and while:
output:
[11, 12, 15]
[]
But my question here is, what is the difference made by while loop rather than for loop (I know solution with for loop is larger than while loop here, but please tell me difference made)
xxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxx
Second question on the same function :
if I used the “for” loop and make the solution as follows:
def delete_starting_evens(lst):
for num in lst:
if lst[0] % 2 == 0:
del lst[0]
return lst
here I used the del function to remove the first element in the list which works fine if a list contains even as well as odd numbers, but if it contains all even numbers it should remove every even number from list and return an empty list, but it is not returning empty list as in this example below:
print(delete_starting_evens([4, 8, 10]))
it gives output as:
[10]
rather than creating an empty list.
Please reply with an explanation of both questions.