Python Program on List Methods

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we will explore four Python programs that focus on different aspects of list manipulation. These programs cover topics such as exception handling, basic list operations, sorting, and removing elements from a list. By examining these examples, readers will gain practical insights into handling lists in Python and dealing with common scenarios that arise during list operations.

Prerequisites

  • Basic understanding of Python programming language.
  • Familiarity with list data structure in Python.
  • Knowledge of fundamental concepts such as loops, user input, exception handling, and basic operations in Python.

Topic Explanation

Program 1: Exception Handling with Lists

Beyond its core functionality, Program 1 serves as a valuable lesson in writing robust and error-tolerant code. The intricacies of exception handling are further illuminated, demonstrating the importance of anticipating and gracefully managing errors during list operations. Through this, readers gain not only technical skills but also a mindset for resilient programming practices.

Code:

# Define a list containing a mix of integers, strings, and floats
mylist = [10, "apple", 25, "banana", 5, "cherry", 30, "date"]

try:
    # Get user input for the index number
    i = int(input("Enter Index number: "))

    # Get user input for a number (b) to perform division
    b = int(input("Enter a number: "))

    # Try to perform integer division on the element at the specified index
    result = mylist[i] // b

    # Print the result of the division
    print(result)

# Handle the case where the user enters a non-integer value
except ValueError:
    print("Enter number only")

# Handle general exceptions (other than ValueError)
except Exception:
    print("Error in Program.....")

# Handle the case where the user provides an invalid index
except IndexError as obj:
    print("Invalid index number....")

# Handle the case where division by zero is attempted
except ZeroDivisionError as obj:
    print("Can't divide by zero....")

Input and Output:

Enter Index number: 10
Enter a number: 3
Error in Program…..

Code Explanation:

Defines a list mylist containing a mix of integers, strings, and floats

1. Uses a try block to attempt:

  • Get user input for an index into the list to access
  • Get user input for a number b to divide the accessed element by
  • Perform integer division using // on accessed element and b
  • Print the division result

2. Uses except blocks to handle different exceptions:

  • ValueError if user enters a non-integer value for inputs
  • Exception to catch general exceptions
  • IndexError if user enters an invalid index into the list
  • ZeroDivisionError if user enters 0 for b, attempting to divide by 0

3. The except blocks print custom error messages for each exception type encountered
4. This shows how to anticipate and handle different exceptions in Python using try and except blocks

Program 2: Basic List Operations

Program 2 not only provides foundational insights into list traversal and length calculation but also sets the stage for more advanced manipulations. The simplicity of basic operations becomes a stepping stone for readers to embark on a journey of increasingly complex list handling, laying a solid groundwork for subsequent programs.

Code:

# Define a list containing a mix of integers, strings, and floats
mylist = [10, "apple", 25, "banana", 5, "cherry", 30, "date"]

# x stores length of list
x = len(mylist)

# Print the length of the list
print(x)

# Iterate over the elements in the list using a for loop
for i in range(0, len(mylist), 1):
    # Print each element with a space at the end to display them on the same line
    print(mylist[i], end=" ")
Output:
8
10 apple 25 banana 5 cherry 30 date

Code Explanation:

1. Defines a list mylist containing integers, strings, and floats
2. Uses the len() function to get the length of mylist and stores it in x
3. Prints out x to display the length of the list
4. Sets up a for loop to iterate through the elements in mylist:

  • The range() function returns numbers from 0 to length of list – 1
  • This number sequence will serve as the loop indexes

5. Inside the loop:

  • Indexes into mylist using the loop variable i to access each element
  • Prints each element followed by a space to display outputs on same line

6. So this iterates through the list and prints all elements by accessing them via an index in the loop

Program 3: List Insertion, Sorting, and Reversal

With Program 3, the narrative of list manipulation takes a dynamic turn. The process of initializing an empty list, user-driven population, and subsequent modifications through insertion, sorting, and reversal reflects the real-world scenarios where lists are continually evolving. This program serves as a bridge between fundamental operations and advanced list manipulations.

Code:

# Initialize an empty list
mylist = []

# Get user input for the limit of the list
n = int(input("Enter the limit:"))

# Use a for loop to iterate 'n' times and append user inputs to the list
for i in range(n):
    x = input()
    mylist.append(x)

# Print the list after user inputs
print("List after user inputs:", mylist)

# Inserting the value 600 at index 3 
mylist.insert(3, 600)

# Print the list after inserting 600
print("List after inserting 600 at index 3:", mylist)

# Print the list before sorting
print("Before Sorting:")
print(mylist)

# Check if the elements are of comparable types (either all strings or all integers)
if all(isinstance(elem, (int, str)) for elem in mylist):
    # Convert elements to integers if they are strings
    mylist = [int(elem) if isinstance(elem, str) else elem for elem in mylist]

    # Sorting the list 
    mylist.sort()

    # Print the list after sorting
    print("After Sorting:")
    print(mylist)
else:
    print("Elements are not of comparable types.")

# Reverse the order of elements in the list
mylist.reverse()

# Print the list after reversing the order
print("After Reversing:")
print(mylist)
Output:
Enter the limit:5
1
2
5
4
3
List after user inputs: [‘1’, ‘2’, ‘5’, ‘4’, ‘3’]
List after inserting 600 at index 3: [‘1’, ‘2’, ‘5’, 600, ‘4’, ‘3’]
Before Sorting:
[‘1’, ‘2’, ‘5’, 600, ‘4’, ‘3’]
After Sorting:
[1, 2, 3, 4, 5, 600]
After Reversing:
[600, 5, 4, 3, 2, 1]

Code Explanation:

1. Initializes empty list mylist to store user inputs
2. Gets integer user input for n, the desired limit on number of inputs
3. Sets up a for loop to iterate n times:
I) Each iteration:

  • Gets next user input as string and stores in x
  • Appends x to my list using .append() method

4. Prints current mylist showing user inputs
5. Inserts integer 600 at index 3 in the list using .insert() method
6. Prints mylist again showing inserted value 600
7. Prints message “Before Sorting”
8. Prints current unsorted mylist
9. Check if all elements in my list are comparable types:

  • Uses all() and isinstance() to check if all are int or str

10. If all comparable types:

  • Converts any str elements to int using conditional list comprehension
  • Sorts list in ascending order using .sort() method

11. Prints message “After Sorting”
12. Prints sorted version of my list
13. If not all comparable types, prints error message
14. Reverses current order of elements using .reverse()
15. Prints message “After Reversing”
16. Prints list with reversed element order

Program 4: List Removal Operations

As readers traverse the landscape of list manipulation, Program 4 becomes a crucial chapter. It not only showcases the practicality of removing elements but also draws attention to the nuances between pop() and remove(). The user-centric removal operations contribute to a holistic understanding of efficiently modifying lists based on specific needs.

Code:

# Initialize an empty list
mylist = []

# Get user input for the limit of the list
n = int(input("Enter the limit:"))

# Use a for loop to iterate 'n' times and append user inputs to the list
for i in range(n):
    x = input()
    mylist.append(x)

# Print the list after user inputs
print("List after user inputs:", mylist)

# Remove the last element from the list using the pop() method
mylist.pop()

# Print the list after removing the last element
print("List after popping the last element:", mylist)

# Get user input for the element to be removed
n = input("Enter element for removal: ")

# Remove the specified element from the list using the remove() method
mylist.remove(n)

# Print the list after removing the specified element
print("List after removing element '{}':".format(n), mylist)

Output:

Enter the limit:4
1
2
3
4
List after user inputs: [‘1’, ‘2’, ‘3’, ‘4’]
List after popping the last element: [‘1’, ‘2’, ‘3’]
Enter element for removal: 2
List after removing element ‘2’: [‘1’, ‘3’]

Code Explanation:

  • Initializes an empty list mylist
  • Gets user input for n, the desired limit on number of elements
  • Uses a for loop to append n user inputs to mylist
  • Prints mylist after taking user inputs
  • Removes last element from mylist using .pop() method
  • Prints mylist after removing last element
  • Gets user input for element to remove in n
  • Removes user-specified element n from mylist using .remove()
  • Prints mylist after removing element n

Summary

This article explored four Python programs, each focusing on different aspects of list manipulation.

Program 1 demonstrated effective exception handling during list operations, showcasing the use of try-except blocks to gracefully manage errors.

Program 2 covered basic list operations, emphasizing list traversal and length calculation.

Program 3 illustrated list insertion, sorting, and reversal, providing practical insights into modifying lists dynamically.

Lastly, Program 4 demonstrated list removal operations using pop() and remove() methods.

Overall, these examples offered valuable insights into handling common scenarios when working with lists in Python, making it a useful resource for individuals seeking practical experience in list manipulation.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *