Python Forum
defining a function to see if a list is sorted - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: defining a function to see if a list is sorted (/thread-14417.html)

Pages: 1 2


RE: defining a function to see if a list is sorted - ichabod801 - Nov-29-2018

A note on looping through consecutive items of a list:

for first, second in zip(the_list, the_list[1:]):
    if first > second:
        return False
return True
That does give a performance hit because you are creating a new list. For small lists that shouldn't be a big issue. If large lists are a possibility you can use islice from itertools.


RE: defining a function to see if a list is sorted - Gribouillis - Nov-29-2018

ichabod801 Wrote:If large lists are a possibility you can use islice from itertools.
Using itertools, the function would rather look like
from itertools import tee

def is_sorted(iterable):
    a, b = tee(iterable)
    next(b, None)
    return all(x <= y for x, y in zip(a, b))
It doesn't work only for lists, but for all iterables.


RE: defining a function to see if a list is sorted - Siylo - Nov-29-2018

Thank you very much. I am going to save these in my notes. We haven't covered anything like this in class, it's a first programming class, but I like to play with new things and push the limits of what I know as far as I can. Sometimes I over think things and make them much harder than it really is, which is what I did with this project. Long days and upcoming finals have fried my brain and I miss the easy answer that's right in front of me. You guys do a great job of running these forums. It's nice to have a place to go to get some help and answers/tips. I'm never looking for someone to do it for me, sometimes I just need to be steered in the right direction. Thanks again!!


RE: defining a function to see if a list is sorted - Larz60+ - Nov-29-2018

good attitude!


RE: defining a function to see if a list is sorted - wavic - Nov-29-2018

You are not going to learn all of this at school. I am happy to see one who enjoy learning and hungry to expanding his knowedge.