In the previous article we discussed handling of slicing on tuples, strings and lists in python. Now let us explore how we can handle a problem related to list concept. We need to write a function that takes a list as input, also takes a value for ‘x’ as input. The function should return all the elements that are smaller than the value of the ‘x’ specified by the user and make a new list out of these elements.
For example with a list l=[8,100,20,40,3,7] and the input of x as 10. We see that the elements smaller than the specified input of 10 are: 8,3,7. Hence the program’s function should handle provided lists in a similar manner.
Implementation of Program to return Smaller list Elements
def getSmaller(l,x):
res= []
for e in l:
if e < x:
res.append(e)
return res
l=[8,100,20,40,3,7]
x=10
print(getSmaller(l,x))
Output:
[8, 3, 7]
In the above program, the function takes two input values as parameters from the user. The value of l for list and x as the separate number which the elements should be smaller than. It initializes the list as an empty list, It then traverses through every element of the list and for every item it checks if it is smaller than x. If it is smaller than x we append it to the new list, if not we simply discard it. At the end we return the resultant list.
Thus we have seen how we can implement program to return Smaller List Elements, in the next article we will explore how we can separate even & odd list items.