Python Program to Check if a List is Sorted

Aim: Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise.

Program:

def is_sorted(a):
    for i in range(len(a) - 1):
        #print(a[i], a[i + 1])
        if a[i] <= a[i + 1]:
            return True
        else:
            return False
print(is_sorted([1,2,3,4]))

# false list -print(is_sorted([5,1,3,2]))

Output:

True

Sample Viva Questions and Answers

1. What is the purpose of the is_sorted function?
The purpose of the is_sorted function is to determine if a given list is sorted in ascending order, returning True if it is and False otherwise.

2. How does the function check if the list is sorted?
The function iterates through the list and compares each element with the next one. If it finds any element that is greater than the next, it returns False.

3. What will the function return for the input list [1, 2, 3, 4]?
The function will return True, as the list is sorted in ascending order.

4. What is the output of the function when called with the list [5, 1, 3, 2]?
The function will return False, as the list is not sorted in ascending order.

5. What is the significance of the loop running from 0 to len(a) - 1?
The loop runs from 0 to len(a) - 1 to ensure that each element is compared with the next one without going out of bounds.

6. Why does the function return True immediately upon finding the first pair of elements that are in order?
This is a logical error in the code. The function should continue checking all pairs before returning True. It should only return True after confirming that all elements are in order.

7. How would you modify the function to correctly determine if the list is sorted?
You should return True only after the loop completes without finding any unsorted pairs. The correct implementation would look like this:

def is_sorted(a):
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
return False
return True
 

8. What will happen if the input list is empty?
The function will return True, as an empty list is considered sorted by definition.

9. Can you explain the time complexity of the is_sorted function?
The time complexity of the function is O(n), where n is the number of elements in the list, as it may need to check each element once.

10. How can you enhance the function to handle lists with mixed data types?
To enhance the function, you could add type checking to ensure that all elements are comparable, or you could handle specific types of data (e.g., numbers and strings) separately.

📌 Python Programming Lab – Complete Guide

Welcome to the Python Programming Lab! This comprehensive lab series is designed to provide a solid foundation in Python programming through practical exercises and hands-on learning. From basic calculations to advanced concepts like file handling, modules, and GUI programming, this lab covers it all. Let’s dive into what you’ll be learning throughout this lab course.


🔍 Week 1: Introduction to Python Basics

In the first week, you will explore fundamental Python concepts aimed at building a strong foundation for your programming journey.

  • Getting Started with Python: Visit the Python Official Website to explore documentation and use the help() function in the interpreter.
  • Python as a Calculator: Learn how to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Calculating Compound Interest: Write a program to calculate compound interest using the formula with given principal, rate, and time.
  • Distance Calculation: Compute the distance between two points using the distance formula.
  • Reading User Details: Write a program to collect and print user details like name, address, email, and phone number.

🔍 Week 2: Python Loops and Conditional Statements

This week focuses on using loops and conditional statements effectively.

  • Pattern Generation: Print a triangle pattern using nested loops.
  • Character Identification: Write a program to identify whether the input is a digit, lowercase, uppercase, or special character.
  • Fibonacci Sequence Generation: Use a while loop to generate the Fibonacci series.
  • Prime Numbers Identification: Find all prime numbers within a specified range using the break statement.

🔍 Week 3: Data Structures and Functions

Dive into data structures and creating functions to enhance your programming skills.

  • Converting Lists and Tuples to Arrays: Understand how to convert different data structures.
  • Finding Common Values: Compare two arrays to find common values.
  • Calculating GCD: Create a function to calculate the greatest common divisor (GCD) of two numbers.
  • Palindrome Checker: Write a function that checks if a given string is a palindrome.

🔍 Week 4: Advanced Functions and String Manipulation

This week emphasizes sorting, handling duplicate elements, and manipulating strings effectively.

  • Checking Sorted Lists: Write a function to check if a list is sorted.
  • Handling Duplicates: Create functions to detect and remove duplicates from lists.
  • Dictionary Inversion: Write a program to swap keys and values in a dictionary.
  • String Manipulation: Add commas between characters, remove words from strings, and convert sentences to title case without using built-in functions.
  • Binary String Generation: Use recursion to generate all binary strings of a specified length.

🔍 Week 5: Working with Matrices and Modules

Learn to work with matrices and create custom modules for various applications.

  • Matrix Operations: Define, print, add, and multiply square matrices using Python.
  • Creating Modules: Build modules using geometrical shapes and their operations.
  • Exception Handling: Implement exception handling for robust error management.

🔍 Week 6: Object-Oriented Programming and Validation

This week focuses on using classes, inheritance, and validation techniques.

  • Drawing Shapes with Classes:
    • Create classes for rectangles, points, and circles, and draw them on a canvas.
    • Add colors and attributes to these shapes to enhance visualization.
  • Method Resolution Order (MRO): Demonstrate MRO in multiple inheritance scenarios.
  • Data Validation: Write programs to validate phone numbers and email addresses.

🔍 Week 7: File Handling and Text Processing

Master file handling techniques and analyzing text data.

  • File Merging: Combine the contents of two files into a new file.
  • Word Search: Create a function to find specific words in a file.
  • Word Frequency Analysis: Identify the most frequent words in a text file.
  • Text Statistics: Count words, vowels, blank spaces, lowercase, and uppercase letters in a file.

🔍 Week 8: Python Libraries and GUI Programming

Explore advanced Python libraries and build simple graphical user interfaces.

  • NumPy, Plotly, and Scipy: Learn how to install and use these powerful libraries for data analysis and visualization.
  • Digital Logic Gates: Implement logic gate operations such as AND, OR, NOT, and EX-OR.
  • Adder Circuits: Create programs for Half Adders, Full Adders, and Parallel Adders.
  • GUI Programming: Build a simple window wizard with text labels, input fields, and buttons using Python’s GUI tools.

🌟 Conclusion:

The Python Programming Lab R23 provides you with a strong foundation in Python programming through a wide range of exercises, from basic concepts to advanced topics. By the end of this lab, you will have gained valuable skills in data processing, file handling, OOP, modules, and GUI development. Start coding and enhance your Python skills! 🚀


;