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
#1
I am trying to define a function called isSorted that should take a list as an argument an return True if it is sorted and False if it is not sorted. I've tried to look up videos for help and haven't found any relevant ones. The problem I am having is how to check the value of an index against the previous one to see if it is larger. Can anyone give me an idea on how to do this?

def isSorted(list):
    previous_number = 0
    for i in list:
        value = list[i]
        if value - previous_number >= 0:
            previous_number = list[i]
            return True
        else:
            return False


lyst = [1,2,3,4,5,6,7,8,9]

isSorted(lyst)
this is what I have come up with but when I print it out it is always true, even when i make the list unsorted.
Reply


Messages In This Thread
defining a function to see if a list is sorted - by Siylo - Nov-29-2018, 02:06 AM

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