Helen
Helen

Reputation: 89

Python function that returns values from list smaller than a number

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

Answers (3)

mhawke
mhawke

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

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

Mikhail M.
Mikhail M.

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

Related Questions