Python Forum
defining a function to see if a list is sorted
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
defining a function to see if a list is sorted
#11
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
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.
Reply
#13
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!!
Reply
#14
good attitude!
Reply
#15
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  A function that checks if the list is sorted pooyan89 16 16,575 Apr-22-2024, 09:14 AM
Last Post: DeaD_EyE
  How to Sorted and display the Subclasses of BaseException Fernando_7obink 9 3,712 Feb-10-2021, 12:04 PM
Last Post: buran
  Defining x and y axes in Spectrogram Function amy5678 3 2,276 Nov-29-2020, 01:42 PM
Last Post: jefsummers
  Functions returns content of dictionary as sorted list kyletremblay15 1 2,046 Nov-21-2019, 10:06 PM
Last Post: ichabod801
  python 3.4.3 Question a defining function student8 1 4,328 Oct-02-2017, 07:59 PM
Last Post: nilamo
  sorted list not displaying Crackity 6 5,080 Jul-18-2017, 12:50 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020