3

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]
0

7 Answers 7

5

You can use list-comprehension to do that:

my_list = [1,9,7,3,6]
result = sorted([x for x in my_list if x < 7])
Sign up to request clarification or add additional context in comments.

Comments

4
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!

1 Comment

You don't need a list comprehension. new_list = sorted(x for x in old_list if x < my_int)
4

Lists have a sort method:

old_list = [1,9,7,3,6]
new_list = [x for x in old_list if x < 7]
new_list.sort()

Comments

3

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.

1 Comment

Note that it is only faster for small lists. For big ones the generator is slightly faster. Also interestingly using filter() instead is always slower.
3

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]

1 Comment

Note that this is quite inefficient: You sort the full list (instead of the filtered one), you sort it twice and then you traverse it to find the index to truncate it. This of course only matters for much bigger lists.
1
aa = filter(lambda x: x < 7, [1,9,7,3,6])
aa.sort()
print aa

OUTPUT:
[1, 3, 6]

Comments

1

You can use list comprehension as follow

mylist = [11, 16, 9, 6, 3, 15, 1, 18, 7, 10, 13, 5, 12, 2, 0, 4, 19, 14, 17, 8]
[x for x in sorted(mylist) if x<7]

Result:

[0, 1, 2, 3, 4, 5, 6]

Hope that helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.