w3resource

Python: Check whether a specified list is sorted or not using lambda


Write a Python program to check whether a specified list is sorted or not using lambda.

Sample Solution:

Python Code :

# Define a function 'is_sort_list' that checks if a list 'nums' is sorted based on a specified 'key' function
def is_sort_list(nums, key=lambda x: x):
    # Iterate through the elements of the 'nums' list starting from the second element
    for i, e in enumerate(nums[1:]):
        # Compare the current element with the previous one based on the 'key' function
        if key(e) < key(nums[i]):
            # If the current element is smaller than the previous one, return False
            return False
    
    # If the loop completes without returning False, return True indicating the list is sorted
    return True

# Create a list 'nums1' already sorted in ascending order
nums1 = [1, 2, 4, 6, 8, 10, 12, 14, 16, 17]

# Print the original list 'nums1'
print("Original list:")
print(nums1)

# Check if 'nums1' is sorted and print the result
print("\nIs the said list sorted?")
print(is_sort_list(nums1))

# Create a list 'nums2' that is not sorted
nums2 = [2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2]

# Print the original list 'nums2'
print("\nOriginal list:")
print(nums2)

# Check if 'nums2' is sorted and print the result
print("\nIs the said list sorted?")
print(is_sort_list(nums2))

Sample Output:

Original list:
[1, 2, 4, 6, 8, 10, 12, 14, 16, 17]

Is the said list is sorted!
True

Original list:
[1, 2, 4, 6, 8, 10, 12, 14, 16, 17]

Is the said list is sorted!
False

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to filter the height and width of students, which are stored in a dictionary using lambda.
Next: Write a Python program to extract the nth element from a given list of tuples using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.