I am trying to write a function to check whether a list is sorted (returning True
or False
). How can I avoid multiple variables pointing to the same thing?
def is_sorted(t):
a = t
a.sort()
When I do that, it sorts both a
and t
. How can I avoid this?
Credit for this minimal answer belongs to @gnibbler
EDIT: Please see this answer for the proper way to do it. I'll leave my answer here for posterity (what's the correct way of handling this situation?), but it should not be considered the best answer to the question, even if it is a correct answer to the question.
To answer your specific question, you can use
copy.copy
(or use the slice syntax[:]
) to create a copy of the original list:However, a better method would be to use the
sorted
function to return a sorted copy of the list:Or:
is_sorted = lambda t: sorted(t) == t
This is a very poor way, in terms of performance, to check that a list is ordered. You should instead iterate over it checking that each element is greater or equal to the previous.
Here is the O(n) way to do it
It shortcircuits, so if the list is unsorted right near the beginning it will be very fast
Here is a simple program to compare some of the alternatives
You can either make a copy of
t
and then sort, like so:a = t[:]
, or usesorted
, which returns a new sorted list.Alternatively, you could make use of the
sortedlist
structure from blist, then your list will always be sorted.by creating a copy of your list with something like this: