I need to write a function of all_gt(nums, n)
which nums is a list of number, n is a number, returns the list of numbers from nums that are greater than n. The order of elements should be preserved.
What I need to do is write in .append
format and start by initializing the result to an empty list.
For example:
all_gt([1,2,3,4],4) => []
all_gt([2,3,4,5], 3) => [4,5]
This is what I have:
def all_gt(nums, n):
for i in nums:
if i > n:
return nums.append(i)
I know what I did is wrong and I hope someone can help me solve this question.
3 Answers 3
Your mistake
return nums.append(i)
appends a value to the list in-place and returns None
. A workaround can be
def all_gt(nums, n):
num2 = []
for i in nums:
if i > n:
num2.append(i)
return num2
Better Ways
You can use a list comprehension
def all_gt(nums, n):
return [i for i in nums if i > n]
3 Comments
num2 = []
statement after the function definitionYou can use filter
to keep only the elements greater than n
:
>>> def all_gt(nums, n):
... return filter(lambda x: x > n, nums)
>>> all_gt([1, 2, 3, 4], 4)
[]
>>> all_gt([2, 3, 4, 5], 3)
[4, 5]
4 Comments
just applying list comprehension with a if condition will do the trick
nums = [ 1, 2, 3, 4, 5]
constraint = 3
filtered_result = [ x for x in nums if x > constraint]
will result into [4,5]
i
that are greater thann
to that new list. After the for loop ran, return the new list.append
returnsNone
and modifiesnums
. Second, you need to construct a new list and this is absent from your code. Third, you need to return once all the required elements are added to the list, in your code you will return after one element is added to your list. Fourth you should look at idiomatic ways of iterating over lists in Python using list comprehensions, even if your assignment requires you to useappend
.