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:
List<int> notas = [85, 92, 78];

Adding Elements

Add new elements to your list using the add() method:
notas.add(95);
print(notas); // [85, 92, 78, 95]

Displaying Lists

You can print the entire list at once:
print(notas); // [85, 92, 78, 95]
Use a for-in loop to iterate through each element:
for (int nota in notas) {
  print(nota);
}
Output:
85
92
78
95
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:
int suma = 0;
for (int nota in notas) {
  suma += nota;
}

Computing the Average

Divide the sum by the number of elements using the length property:
double promedio = suma / notas.length;
print('Promedio: $promedio');
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:
void main() {

  List<int> notas = [85, 92, 78];

  // Agregar una nota
  notas.add(95);

  //Imprimir la lista
  print(notas);
  print('');

  // Mostrar todos los elementos de las lista por medio de iteraciones.
  for (int nota in notas) {
    print(nota);
  }

  // Calcular promedio
  int suma = 0;
  for (int nota in notas) {
    suma += nota;
  }
  double promedio = suma / notas.length;
  print('Promedio: $promedio');
}
Output:
[85, 92, 78, 95]

85
92
78
95
Promedio: 87.5

Common List Operations

OperationMethod/PropertyDescription
Add elementadd(value)Adds a single element to the end
Get sizelengthReturns the number of elements
Iteratefor-in loopAccess each element sequentially
Access elementlist[index]Get element at specific position
CalculateLoop + accumulatorSum, average, or other calculations

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:
if (notas.isNotEmpty) {
  double promedio = suma / notas.length;
}
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

Build docs developers (and LLMs) love