Asked  7 Months ago    Answers:  5   Viewed   31 times

list.sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list.

  • When is one preferred over the other?
  • Which is more efficient? By how much?
  • Can a list be reverted to the unsorted state after list.sort() has been performed?

 Answers

77

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

Tuesday, June 1, 2021
 
BradM
answered 7 Months ago
93

Here is one way to do this:

>>> sorted(myDict.items(), key=lambda e: e[1][2])
[('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]

The key argument of the sorted function lets you derive a sorting key for each element of the list.

To iterate over the keys/values in this list, you can use something like:

>>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]):
...   print key, value
... 
item2 [8, 2, 3]
item1 [7, 1, 9]
item3 [9, 3, 11]
Thursday, June 3, 2021
 
binoculars
answered 7 Months ago
14

Yes - their performance characteristics differ significantly. It would probably be better to call them SortedList and SortedTree as that reflects the implementation more closely.

Look at the MSDN docs for each of them (SortedList, SortedDictionary) for details of the performance for different operations in different situtations. Here's a nice summary (from the SortedDictionary docs):

The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to the SortedList<TKey, TValue> generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList<TKey, TValue> uses less memory than SortedDictionary<TKey, TValue>.

  • SortedDictionary<TKey, TValue> has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) for SortedList<TKey, TValue>.

  • If the list is populated all at once from sorted data, SortedList<TKey, TValue> is faster than SortedDictionary<TKey, TValue>.

(SortedList actually maintains a sorted array, rather than using a tree. It still uses binary search to find elements.)

Sunday, June 6, 2021
 
erotsppa
answered 6 Months ago
26

Typically, there are two key differences between get_the_* and the_* functions.

  1. get_the_* methods don't echo anything themselves. Instead, they return the value that you're interested in, normally as a string. For example, get_the_time() echoes nothing, and returns a string representation of the posting time of the current post. the_* methods directly output the same value, without you having to echo it; the_time() returns nothing, but directly echoes the posting time.

  2. the_* methods are generally designed to be used inside the Loop, so they often don't take a parameter to specify which post you're asking about; for example, the_title() doesn't take a post_id parameter, and can therefore only act on the "current" post inside the Loop. It doesn't make sense to call it outside the loop—which post would it be getting the title for? However, get_the_title() takes a post ID as a parameter, so you can use it from anywhere to get the title of any post, as long as you've got the post's ID. (Many of the get_the_ methods take an optional post id parameter, and default to returning the value for the current post if they're used from in the Loop, for convenience.)

Because WordPress has been in development for so many years, and things have gradually been added, these aren't guaranteed rules, and you'll find exceptions here and there. You should take this as general advice and check the documentation for each specific instance as you need it.

Saturday, July 31, 2021
 
Optimight
answered 4 Months ago
66

General solution: use list.sort with a key function returning a tuple:

mylist.sort(key=lambda sl: (sl.count('YES') + sl.count('MAYBE'), -sl.count('NO')), reverse=True)

key and reverse were added in Python 2.4, so you'll have to do it manually:

key = lambda sl: (sl.count('YES') + sl.count('MAYBE'), -sl.count('NO'))
mylist.sort(lambda p, q: -cmp(key(p), key(q)))

If key is slow it's best to use a solution that computes the key function on each item only once (a so-called "Schwartzian transform"). Note that >=Python 2.4 perform this optimisation (or similar) already:

def key_sort(seq, cmp=None, key=None, reverse=False):
    if key is not None:
        transform = [(key(x), i, x) for i, x in enumerate(seq)]
        transform.sort(None if cmp is None else lambda (k, _, _), (l, _, _): cmp(k, l))
        seq[:] = [x for _, _, x in transform]
    else:
        seq.sort(cmp)
    if reverse:
        seq.reverse()
Wednesday, December 1, 2021
 
Jeremy
answered 3 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share