Reputation: 89
My function needs to take in a list of integers and a certain integer and return the numbers in the list that are smaller than the specific integer. Any advice?
def smallerThanN(intList,intN):
y=0
newlist=[]
list1=intList
for x in intList:
if int(x) < int(intN):
print(intN)
y+=1
newlist.append(x)
return newlist
Upvotes: 4
Views: 4043
Reputation: 87084
Use a list comprehension with an "if" filter to extract those values in the list less than the specified value:
def smaller_than(sequence, value):
return [item for item in sequence if item < value]
I recommend giving the variables more generic names because this code will work for any sequence regardless of the type of sequence's items (provided of course that comparisons are valid for the type in question).
>>> smaller_than([1,2,3,4,5,6,7,8], 5)
[1, 2, 3, 4]
>>> smaller_than('abcdefg', 'd')
['a', 'b', 'c']
>>> smaller_than(set([1.34, 33.12, 1.0, 11.72, 10]), 10)
[1.0, 1.34]
N.B. There is already a similar answer, however, I'd prefer to declare a function instead of binding a lambda expression.
Upvotes: 4
Reputation: 4021
integers_list = [4, 6, 1, 99, 45, 76, 12]
smallerThan = lambda x,y: [i for i in x if i<y]
print smallerThan(integers_list, 12)
Output:
[4, 6, 1]
Upvotes: 0
Reputation: 5968
def smallerThanN(intList, intN):
return [x for x in intList if x < intN]
>>> smallerThanN([1, 4, 10, 2, 7], 5)
[1, 4, 2]
Upvotes: -1