Why is len(lst) > 0 necessary for solving the list challenge?

Hi, I have some question on this one.
1)Does lst[0] means that every number in the list are processed by the loop?
2) Why is the code “len(lst) > 0” crucial in the loop?

4 Likes

This could be wrong im a noob but I think this is why:

  1. lst[0] is basically selecting the 0 ‘index’ in the list = [1, 2, 3] int 1 is index 0, int 2 is index 1 etc … so when it loops after slicing the first even number

lst = lst(1:)

the lst index 0 will also change! Our lst here will become lst = [2, 3] with 0 index now being int 2. The loop will then iterate again and again until…

This … 2) len(lst) > 0 is crucial because if we don’t we enter in to an infinite loop? or something imagine if the list was all even integers once the loop has checked all the integers it has none to check which I think would create an infinite loop.

Sorry I could be a million percent wrong! But thought i’d try for my own benefit as well as yours!

Happy coding :slight_smile:

5 Likes

@ajikhan7086997408 your solution is correct, thank you!

Not quite. There will be no infinite loop, but instead an IndexError will be raised.

The purpose of checking that the length is greater than zero is to prevent attempting to access an index of an empty list–There are no indices to access.

2 Likes

@mtf but here in the last exercise, in which scenario we will attempt to access an index of an empty list .
This worked for me
#Write your function here
def delete_starting_evens(lst) :
for number in lst :
print (number)
if number % 2 == 0 :
lst = lst[1:]
else :
break
return lst

#Uncomment the lines below when your function is done
#print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))

Consider the possibility we are not accessing an empty list, but simply not running a loop on one.

@mtf Please elaborate with example

>>> for x in []:
	print (x)
else:
	print ("Empty list")

	
Empty list
>>> 

What this demonstrates is that the loop does not execute on the empty list.


Aside

Until we see how your code is indented, we cannot provide an example based upon it. I’m pointing at mere details, for the moment.


… to continue,

>>> [][1:]
[]
>>> 

This demonstrates that slice is a method of the list object. It must have its own fail check in determining the returned list, since a list is what gets returned.

>>> for x in []:
	print (x)
else:
	print ([][1:])

	
[]
>>> 

>>> print ([][0])

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    print ([][0])
IndexError: list index out of range
>>> print ([][0:])
[]
>>> 

def delete_starting_evens(lst):
while (len(lst)>0):
if lst[0] % 2 == 0:
lst = lst[1:]
return lst

will this create a infinite loop?

Welcome, @harishramesh6788,

If the first value in the list is odd, then yes. Further, if the list contains any odd numbers, it will loop forever since the list length never changes.