Skip to main content

Working with Lists

This guide demonstrates common list operations through a practical example of managing student grades.

Creating and Initializing Lists

Start by creating a list with initial values:

Adding Elements

Add new elements to your list using the add() method:

Displaying Lists

You can print the entire list at once:
Use a for-in loop to iterate through each element:
Output:
The for-in loop is ideal when you need to access each element but don’t need the index position.

Calculating with Lists

Computing the Sum

Iterate through the list to calculate the total:

Computing the Average

Divide the sum by the number of elements using the length property:
The length property automatically tracks the number of elements, so you don’t need to count them manually.

Complete Example

Here’s a complete program that demonstrates list operations:
Output:

Common List Operations

Practical Use Cases

Grade Management

Store and calculate student grades, averages, and statistics

Data Collection

Accumulate data points for analysis and reporting

Inventory Tracking

Track quantities, prices, or stock levels

Score Keeping

Manage game scores, points, or rankings

Best Practices

When calculating averages, always check that the list is not empty to avoid division by zero:
Use descriptive variable names like suma (sum) and promedio (average) to make your code more readable.

Next Steps

Now that you understand basic list operations, you can:
  • Learn different ways to iterate through lists
  • Explore advanced list methods like map(), where(), and reduce()
  • Work with lists of custom objects
  • Combine multiple operations for complex data processing