> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/NormandoRamirezDelgado/6C-Febrero-2026/llms.txt
> Use this file to discover all available pages before exploring further.

# Iterating Lists

> Learn different ways to iterate through lists in Dart using for-in and for loops

## Iterating Through Lists

Iteration is the process of accessing each element in a list sequentially. Dart provides multiple ways to iterate through lists, each suited for different scenarios.

## Using For-In Loop

The `for-in` loop is the simplest way to access each element in a list:

```dart theme={null}
List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa'];

for (var nombre in nombres) {
  print(nombre);
}
```

**Output:**

```
Juan
María
Pedro
Luisa
```

<Info>
  Use `for-in` when you only need to read the values and don't need to know the index position.
</Info>

## Searching While Iterating

You can search for specific elements while iterating through a list:

```dart theme={null}
List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa'];
int posicion = 0;

for (var nombre in nombres) {
  if (nombre == 'Luisa') {
    print('Nombre encontrado en posición $posicion');
  }
  posicion++;
}
```

**Output:**

```
Nombre encontrado en posición 3
```

<Note>
  When using `for-in` and you need the index, you must manually track the position with a counter variable.
</Note>

## Using Indexed For Loop

When you need to modify elements or access indices directly, use a traditional `for` loop:

```dart theme={null}
for (var i = 0; i < nombres.length; i++) {
  if (nombres[i] == 'Maria') {
    nombres[i] = 'María';
  }
}
```

<Warning>
  You cannot modify list elements directly in a `for-in` loop. Use an indexed `for` loop instead when you need to change values.
</Warning>

## Iteration Methods Comparison

| Method        | Use Case              | Can Modify Elements | Has Index                   | Syntax Complexity |
| ------------- | --------------------- | ------------------- | --------------------------- | ----------------- |
| `for-in`      | Reading values        | No                  | No (manual tracking needed) | Simple            |
| Indexed `for` | Modifying elements    | Yes                 | Yes                         | Moderate          |
| `forEach()`   | Functional approach   | No                  | No                          | Simple            |
| `map()`       | Transforming elements | Creates new list    | No                          | Moderate          |

## Complete Example

```dart theme={null}
void main() {
  //Programa para recorrer una lista de diversas maneras utilizando for in y for. 
  List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa', 'Maria'];
  
  //Recorrer o Iterar la Lista
  for (var nombre in nombres) {
    print(nombre);
  }
  
  //Buscar un elemento de la Lista
  int posicion = 0;
  for (var nombre in nombres) {
    if (nombre == 'Luisa'){
      print('Nombre encontrado en posición $posicion');
    }
    posicion++;
  }
  
  //Modificar el valor de un elemento de la lista
  for (var i = 0; i < nombres.length; i++) {
    if (nombres[i] == 'Maria')
      nombres[i] = 'María';
  }

  for (var nombre in nombres) {
    print(nombre);
  }
}
```

## Common Iteration Patterns

### Pattern 1: Simple Iteration

Just access each element:

```dart theme={null}
for (var item in list) {
  print(item);
}
```

### Pattern 2: Search with Position

Find an element and get its index:

```dart theme={null}
int index = 0;
for (var item in list) {
  if (item == searchValue) {
    print('Found at position $index');
    break; // Stop after finding
  }
  index++;
}
```

### Pattern 3: Modify Elements

Change values based on conditions:

```dart theme={null}
for (var i = 0; i < list.length; i++) {
  if (condition) {
    list[i] = newValue;
  }
}
```

### Pattern 4: Filter Elements

Collect matching elements:

```dart theme={null}
List<String> filtered = [];
for (var item in list) {
  if (condition) {
    filtered.add(item);
  }
}
```

## Working with Empty Lists

<Tip>
  Always check if a list has elements before iterating, especially when working with user input:

  ```dart theme={null}
  if (nombres.isNotEmpty) {
    for (var nombre in nombres) {
      print(nombre);
    }
  } else {
    print('La lista está vacía');
  }
  ```
</Tip>

## Advanced Iteration Methods

### Using forEach()

Functional approach with a callback:

```dart theme={null}
nombres.forEach((nombre) {
  print(nombre);
});
```

### Using map()

Transform each element into a new list:

```dart theme={null}
List<String> upperNames = nombres.map((nombre) => nombre.toUpperCase()).toList();
```

### Using where()

Filter elements based on a condition:

```dart theme={null}
List<String> filteredNames = nombres.where((nombre) => nombre.startsWith('M')).toList();
```

## Performance Considerations

<CardGroup cols={2}>
  <Card title="For-In Loop" icon="bolt">
    Most readable and efficient for simple iteration
  </Card>

  <Card title="Indexed For" icon="sliders">
    Best when you need to modify elements or access indices
  </Card>

  <Card title="forEach()" icon="function">
    Good for functional programming style
  </Card>

  <Card title="map/where" icon="filter">
    Ideal for transforming or filtering data
  </Card>
</CardGroup>

## Choosing the Right Method

1. **Use `for-in`** when you just need to read values
2. **Use indexed `for`** when you need to modify elements or use indices
3. **Use `forEach()`** for functional programming style
4. **Use `map()` or `where()`** for transformations and filtering

<Warning>
  Avoid modifying a list's length (adding/removing elements) while iterating through it, as this can cause unexpected behavior or errors.
</Warning>
