Hi please i need some explanation with this code,
why use list [1: 0]? and normally it should return all the elements of the list except those which come before

#Write your function here

def delete_starting_evens(lst):

while (len(lst) > 0 and lst[0] % 2 == 0):

lst = lst[1:]

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]))

So why do we use while (len (lst)> 0 and lst [0]% 2 == 0):

Consider what each of those expressions and slices actually returns. len(lst) is fairly straightforward. lst[0] is the first index of lst but what is the equality doing? Finally what would the slice lst[1:] provide why would this be used following the previous steps?

Work those steps out in your head or on paper with the example lists given, .e.g. [4, 8, 10].

I don’t know how much but here’s what I see;
list [0] returns all the elements of the list since we are in a loop.
list [1:] returns all elements that are part of the second index? well that’s what must have happened but that’s not what I see.

Please explain to me if I’m wrong, because this part list [1:] that I really don’t understand

Actually, lst[0] is only the first element of the list. It is not a slice, though, just an element reference.

lst[1:] is a slice, as indicated by the :. It excludes the first element of the list but includes all the others from the second to the last.


OK, thanks ,
but I don’t understand why it returns [11] so the condition says while lst [0]% 2 == 0 so with 11 the list is not odd so it has to exit the loop.

Also if the list starts from index 1 why it excludes 8

Do you mean the above list returns only [11] and not [11, 12, 15]?

Consider what your code is doing…

[4, 8, 10, 11, 12, 15]

   [8, 10, 11, 12, 15]

      [10, 11, 12, 15]

          [11, 12, 15]  the returned list

No the list returns ca [11, 12, 15] but I don’t understand why. Because list = list [1:] only executes when the number is even

That’s what is expected. It continues to copy a shortened list back onto the variable as long as the number at position 0 is even. Once it reaches an odd number it returns the list that is remaining.

1 Like

ok i’m starting to understand better, list [1:] shortens the list at each even position until it reaches an odd position.

That is to say that a change position list [1:] changes place.
That is to say at index 0 it is at 1
at index 1 there are two?

What exactly do you mean by this?

[start:end:step] returns a slice of a list.

1 Like

What was at index 1 before, goes to index 0 of the new slice.

Yes that’s what I meant it’s understood. what if we want to change the index, ie [2:]

1 Like

That would not really be useful in this instance. We only check the first value, so move up the list one index at a time.

1 Like