A complete example using Python lists to solve practical problems
PythonHere is a complete example using Python lists, demonstrating how to create, manipulate, and utilize lists to solve practical problems.
Example: Student Grade Management System
Problem Description
We need to create a simple student grade management system with the following features:
- Add student grades.
- Calculate the class average grade.
- Find the highest and lowest grades.
- List all passing grades (≥60).
Code Implementation
# Create an empty list to store student grades
student_grades = []
# Add a student grade
def add_grade(grade):
student_grades.append(grade)
print(f"Added grade: {grade}")
# Calculate the class average grade
def calculate_average():
if not student_grades:
return 0
return sum(student_grades) / len(student_grades)
# Find the highest and lowest grades
def find_max_min():
if not student_grades:
return None, None
return max(student_grades), min(student_grades)
# List all passing grades (≥60)
def list_passing_grades():
passing_grades = [grade for grade in student_grades if grade >= 60]
return passing_grades
# Main program
def main():
# Add some student grades
add_grade(85)
add_grade(92)
add_grade(58)
add_grade(73)
add_grade(45)
# Calculate and print the average grade
average_grade = calculate_average()
print(f"Average grade: {average_grade:.2f}")
# Find and print the highest and lowest grades
max_grade, min_grade = find_max_min()
print(f"Highest grade: {max_grade}")
print(f"Lowest grade: {min_grade}")
# List all passing grades
passing_grades = list_passing_grades()
print(f"Passing grades: {passing_grades}")
# Run the main program
if __name__ == "__main__":
main()
Output
Added grade: 85
Added grade: 92
Added grade: 58
Added grade: 73
Added grade: 45
Average grade: 70.60
Highest grade: 92
Lowest grade: 45
Passing grades: [85, 92, 73]
Code Explanation
-
student_grades
List:- Used to store all student grades.
- Grades are added using the
append()
method.
-
add_grade()
Function:- Takes a grade as input and adds it to the
student_grades
list.
- Takes a grade as input and adds it to the
-
calculate_average()
Function:- Calculates the class average grade.
- Uses the
sum()
function to get the total andlen()
to count the number of grades.
-
find_max_min()
Function:- Uses the
max()
andmin()
functions to find the highest and lowest grades.
- Uses the
-
list_passing_grades()
Function:- Uses a list comprehension to filter out all passing grades (≥60).
-
main()
Function:- Calls the above functions to implement the core logic of the grade management system.
Summary
- This example demonstrates how to use Python's
list()
to store and manipulate data. - Lists are highly flexible and ideal for managing dynamic collections of data, such as student grades, task lists, etc.
- By combining list comprehensions and built-in functions like
sum()
,max()
, andmin()
, you can efficiently perform various data processing tasks.