Is python's sorted() function guaranteed to be stable?

how to use is in python
python operator
python is none vs none
difference between / and // in python
difference between = and == in python
difference between / and // in python 3
physical equality python

The documentation doesn't guarantee that. Is there any other place that it is documented?

I'm guessing it might be stable since the sort method on lists is guaranteed to be stable (Notes 9th point: "Starting with Python 2.3, the sort() method is guaranteed to be stable"), and sorted is functionally similar. However, I'm not able to find any definitive source that says so.

Purpose: I need to sort based on a primary key and also a secondary key in cases where the primary key is equal in both records. If sorted() is guaranteed to be stable, I can sort on the secondary key, then sort on the primary key and get the result I need.

PS: To avoid any confusion, I'm using stable in the sense of "a sort is stable if it guarantees not to change the relative order of elements that compare equal".

Yes, the intention of the manual is indeed to guarantee that sorted is stable and indeed that it uses exactly the same algorithm as the sort method. I do realize that the docs aren't 100% clear about this identity; doc patches are always happily accepted!

Difference between == and is operator in Python, Difference between == and is operator in Python​​ The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. # python3 code to. Develop and Deploy Apps with Python On Azure and Go Further with AI And Data Science.

They are stable.

By the way: you sometimes can ignore knowing whether sort and sorted are stable, by combining a multi-pass sort in a single-pass one.

For example, if you want to sort objects based on their last_name, first_name attributes, you can do it in one pass:

sorted_list= sorted(
    key= lambda item: (item.last_name, item.first_name))

taking advantage of tuple comparison.

This answer, as-is, covers the original question. For further sorting-related questions, there is the Python Sorting How-To.

Welcome to, Definition and Usage. The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test​  Take 4 hours to complete 57 online exercises to learn Python for data science.

Python is Keyword, The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and  Learn Python Like a Pro. From The Basics All The Way to Creating your own Apps and Games! Join Over 30 Million Students Already Learning Online With Udemy

The "What's New" docs for Python 2.4 effectively make the point that sorted() first creates a list, then calls sort() on it, providing you with the guarantee you need though not in the "official" docs. You could also just check the source, if you're really concerned.

What is the difference between 'is' and '==' in python, . The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. Output of the first if condition is “True” as both list1 and list2 are empty lists. Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace.

The Python 3.6 doc on sorting now states that

Sorts are guaranteed to be stable

Furthermore, in that document, there is a link to the stable Timsort, which states that

Timsort has been Python's standard sorting algorithm since version 2.3

Python '!=' Is Not 'is not': Comparing Objects in Python – Real Python, operators compare whether two variables refer to the same object in memory. If you keep this distinction in mind, then you should be able to prevent unexpected behavior in your code. In technical terms, Python is an object-oriented, high-level programming language with integrated dynamic semantics primarily for web and app development. It is extremely attractive in the field of Rapid Application Development because it offers dynamic typing and dynamic binding options.

4 Demos of Python if not and not in: The not operator, is will return True if two variables point to the same object, == if the objects referred to by the variables are equal. >>> a = [1, 2, 3] >>> b = a >>> b is a True >​>> b  Python is a general-purpose programming language that can be used on any modern computer operating system. It can be used for processing text, numbers, images, scientific data and just about anything else you might save on a computer.

Is there a difference between "==" and "is"?, Python is a programming language that's soaring in popularity with web and software developers. So should you learn Python? One word: Definitely. Python is a popular general-purpose programming language that can be used for a wide variety of applications. It includes high-level data structures, dynamic typing, dynamic binding, and many more features that make it as useful for complex application development as it is for scripting or "glue code" that connects components together.

Python (programming language), Learn Python > What is Python?In technical terms, Python is an object-oriented, high-level programming language with integrated dynamic semantics primarily . Boom—this is where we get a different result. Python is telling us that c and a are pointing to two different objects, even though their contents might be the same. So, to recap let’s try and break the difference between is and == down to two short definitions: An is expression evaluates to True if two variables point to the same (identical) object.

  • I've found that if I'm sorting tuples or lists, whenever the "primary" sorting keys are equal, it ends up sorting by the "secondary" key. For example, sorted([(1, 2), (1, 1)]) returns [(1, 1), (1, 2)] instead of returning the original input in the same sequence/order. Shouldn't the guarantee of stability mean that it should be returning the original [(1, 2), (1, 1)] input? In that case, you have be explicit and say sorted([(1, 2), (1, 1)], key=lambda t: t[0])
  • Isn't this what is expected in this case? Python is going to compare tuples through all elements by default, not just the first "primary" one. If you only want to sort on the first element, you can pass the key parameter explicitly.
  • @code_dredd this is the expected behavior. The point of stable-sort is sort using a "sorting key" but two different elements that have the same sorting key will be in the same order. The default sorting key for a tuple is all the elements of the tuple.
  • This can have undesired effect if you want to reverse the sort. For example when sorting on products, you may want to first sort on rating (ascending order) and then on price (also ascending). If you reverse this, you want to sort on rating in descending order but on price in ascending order. This doesn't work with this solution.
  • @RemcoWendt: there was no requirement for what you describe. In any case, consider key= lambda item: (-item.rating, item.price) or supplying a cmp instead of a key argument. I'm still not sure about the purpose of your comment, though.
  • Indeed it was not a requirement, but wanted to point out this subtle difference when other people read this and make a choice between your solution or using Python's stable sort feature.
  • I see. In other words, sorting by pairs is clearer and is thus preferable, unless you care about performance. I'd imagine that two stable sorts are somewhat faster than one sort by pairs, though the difference may be negligible - ?
  • @tzot I want to mention, there are always such requirements for stable sorting. For example, I have a list of tuple (rate, comment), the comments are saved in the order of when they are made, and I want to sort by the rate and keep the time order, however, I didn't save the timestamp in the list. To say it briefly, I just want to sort the list by rate, and to keep the comment in the same order.
  • Could you point to where it says so? It says sorted() "works like the in-place list.sort()" and "a newly formed copy is sorted", but I don't see it saying that it internally uses sort().
  • The "copy" that is formed is a list (that's what you get as a return value), and .sort() is called on that list prior to returning. QED. No, it's not an unassailable proof, but until Python has an official standard you won't get that.