It seems like you don't understand the question.
Write a function, sublist
, that takes a list of numbers as the parameter.
This means that if we have this:
def sublist(x):
pass
then x
is going to be a list
— not, as in your example, a number. Also, you don't need to do anything with input()
; you've already got the list, so don't need that line at all.
In the function, use a while
loop to return a sublist of the input list.
Well, Python has a feature called "generators" that let you do this very easily! I'm going to cheat a bit, and not use a while
loop. Instead, I'll use a for
loop:
def sublist(x):
for num in x:
if num == 5:
# we need to stop; break out of the for loop
break
# output the next number
yield num
Now this code works:
>>> for num in sublist([3, 4, 2, 5, 6, 7]):
... print(num)
3
4
2
>>>
However, sublist
doesn't technically return a list. Instead, let's use some MAGIC to make it return a list:
from functools import wraps
return_list = lambda f:wraps(f)(lambda *a,**k:list(f(*a,**k)))
(You don't need to know how this works.) Now, when we define our function, we decorate it with return_list
, which will make the output a list
:
@return_list
def sublist(x):
for num in x:
if num == 5:
# we need to stop; break out of the for loop
break
# output the next number
yield num
And now this also works:
>>> print(sublist([3, 4, 2, 5, 6, 7]))
[3, 4, 2]
>>>
Hooray!