Python Practice › List Programs › Program 69

Is a list sorted?

EasyList Programs · 69 of 100

Write a Python program to check whether a list is sorted in ascending order.

Advertisement
Input
[1, 2, 3, 5, 7, 8, 9], [3, 5, 1, 6, 8, 2, 4]
Output
True False

Approach

  1. Every item must be less than or equal to the next one.

Solution

Python
def is_sorted(items):    return all(a <= b for a, b in zip(items, items[1:])) print(is_sorted([1, 2, 3, 5, 7, 8, 9]), is_sorted([3, 5, 1, 6, 8, 2, 4]))
Output
True False

Line by line

Line 2

Checking neighbours is faster than comparing with sorted(items).

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment