Assume there is a list [1,9,7,3,6]. I want to produce a new list which is sorted and smaller than one of the integers, for example the integer is 7, so the new list should be list:
[1,3,6]
oldList = [1,9,7,3,6]
myInt = 7
newList = sorted([x for x in oldList if x < myInt])
This is a Python "list comprehension" - it looks at each element in oldList and adds it to newList if and only if it's smaller than the integer you've chosen. Additionally, the sorted() method is native in Python.
Here's a good resource for list comprehensions for the future: http://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Hope that helps!
new_list = sorted(x for x in old_list if x < my_int)You can use a list comprehension:
sorted([i for i in [1,9,7,3,6] if i < 7])
You can also use a generator:
sorted(i for i in [1,9,7,3,6] if i < 7)
Note: The list comprehension version executes ~2x faster.
Try this:
num = #some number
new_list = sorted(old_list)[:sorted(old_list).index(num)]
OR Alternative
num = 7
somelist = [3,6,7,1,2,8,9,4,5,12]
somelist.sort()
somelist[:somelist.index(num)]
OUTPUT:
[0, 1, 2, 3, 4, 5, 6]