0

my code and result the tutorial code and result

This is my code

def delete_starting_evens(lst):
    for x in lst:
        if x%2 == 0:
            lst = lst[1:]
        else:
            return lst

print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))

I get:

[11, 12, 15]
None

I was expecting to get:

[11, 12, 15]
[]

Can someone explain this?

Picture one is my trial. Picture two is the standard answer. I try to get an empty list by using my for loop. However, it seems that the [] still satisfy the condition of my for loop and somehow make the [] become a None object. Can someone please explain this?

  • 4
    Give a [mre] **as text** in the question – jonrsharpe Mar 29 '20 at 21:15
  • 1
    What does `None` have to do with the question? The assignment doesn't ask for `None` and you don't return `None`. Why mention `None` at all? – Peter Wood Mar 29 '20 at 21:20
  • Ah, I missed the first image. So, if you don't return while you're in the loop, the function returns after the loop, and returns `None` as you don't specify anything to return. – Peter Wood Mar 29 '20 at 21:23
  • I was expecting to get a [], but it returns None. That's what I am asking. I am surprised the [] didn't break the for loop and return itself. – NomardicRoku Mar 29 '20 at 21:26
  • How dose an empty list [] still satisfy the condition: for x in last: if x%2 == 0: – NomardicRoku Mar 29 '20 at 21:28
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – AMC Mar 29 '20 at 23:21

1 Answers1

2

If all items in the list satisfies the condition x % 2 == 0, the return statement will not be executed, and the function will return the default value of None.

Possible solution: Replace return lst with break, and place return lst at the end of the function.

Terje D.
  • 6,250
  • 1
  • 22
  • 30