2

Hey im new to python. How do you get a portion of a list by the relative value of its sorting key.

example...

list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]
list.sort()
newList = list.split("all numbers that are over 13")
assert newList == [14,15,16]

2 Answers 2

3
>>> l = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]
>>> sorted(x for x in l if x > 13)
[14, 15, 16]

or with filter (would be a little bit slower if you have big list, because of lambda)

>>> sorted(filter(lambda x: x > 13, l))
[14, 15, 16]
Sign up to request clarification or add additional context in comments.

2 Comments

Using lambda with filter and map is silly. The list comprehension form satisfies that so much better.
Note that the result has the numbers in the same order as the original list. If you need them to be sorted you should use sorted(x for x in l if x>13)
3

Use [item for item in newList if item > 13].

There is a decent chance this could be replaced with the generator expression (item for item in newList if item > 13), which filters lazily rather than storing the whole list in memory.


You might also be interested in changing the code just a bit to something like

all_numbers = [11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_sorted_numbers = sorted(number for number in all_numbers if number > 13)

which performs the sorting—a worst case O(n log n) operation—on only the filtered values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.