---
title: "Insert an item into a YAML list in Rust without reformatting"
url: https://recursiveai.org/oneyaml/rust/cookbook/insert-yaml-sequence-item/
description: "Insert a YAML list item at a specific index in Rust while keeping neighboring entries, quotes, spacing, and comments intact."
version: "1.2.0"
---

# Insert an item into a YAML list in Rust without reformatting

**oneyaml** is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/insert-yaml-sequence-item/insert-yaml-sequence-item.zip)

Use `insert_at(1, "check")` to add a second item without touching its neighbors.

```shell
cargo add oneyaml
```

```rust
use oneyaml::Document;

fn main() {
    let yaml = concat!(
        "steps:\n  - 'build'  # first\n",
        "  - \"deploy\" # last\n",
    );
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    doc.get_mut("steps").expect("steps list")
        .insert_at(1, "check")
        .expect("valid insertion");
    print!("{doc}");
}
```

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/insert-yaml-sequence-item/insert-yaml-sequence-item.zip), then `cargo run`.

Requires Rust 1.85 or later. The snippet prints the edited YAML:

```text
steps:
  - 'build'  # first
  - "check"
  - "deploy" # last
```

## The full program

The program inserts an item, then appends one. An index greater than the list length returns `EditError::IndexOutOfBounds`; if `steps` is not a list, the edit returns `EditError::NotASequence`.

```rust
use oneyaml::Document;

fn main() {
    let yaml = concat!(
        "steps:\n  - 'build'  # first\n",
        "  - \"deploy\" # last\n",
    );
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    doc.get_mut("steps").expect("steps list")
        .insert_at(1, "check")
        .expect("valid insertion");
    print!("{doc}");

    // After the insertion there are three items.
    // An index equal to the length appends.
    doc.get_mut("steps").expect("steps list")
        .insert_at(3, "notify")
        .expect("append at the end");
    println!("After appending:\n{doc}");
}
```

`cargo run` prints:

```text
steps:
  - 'build'  # first
  - "check"
  - "deploy" # last
After appending:
steps:
  - 'build'  # first
  - "check"
  - "deploy" # last
  - "notify"
```

## Related recipes

- [Edit YAML and keep its comments](https://recursiveai.org/oneyaml/rust/cookbook/edit-yaml-keep-comments/)
- [Restore a removed YAML node](https://recursiveai.org/oneyaml/rust/cookbook/restore-removed-yaml-node/)

## The short answer

Parse the source as a `Document`, get a mutable handle to the list with `get_mut("steps")`, and call `insert_at(1, "check")`. The index is zero-based and the insertion goes **before** the item at that index. In the example, the `build` and `deploy` lines keep their original quotes and comments, while the inserted string is written as `"check"`.

## How do you write a list in YAML?

A YAML list, or sequence, can be written as indented `-` entries (block style) or inside `[...]` (flow style). Both hold ordered items. In the snippet, `steps` is the key in a mapping, and the indented sequence beneath it is the value. Index `1` means the second item **in that sequence**, not line 1 of the file. Blank lines and comments don’t count as items. See the [YAML 1.2.2 collection styles](https://yaml.org/spec/1.2.2/#chapter-7-flow-style-productions) for the syntax.

For example, if `steps` has three items after insertion, `insert_at(3, ...)` appends. `insert_at(4, ...)` is out of bounds. The [insertion API](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/edit.rs#L8018-L8035) returns a handle to the item it inserted, not to the item shifted to the next position. If your intent is to change the second item rather than shift it, `replace_at(1, ...)` is a separate operation.

## How do you update a YAML list without changing its indentation?

Edit the parsed document instead of deserializing the list into a `Vec` and serializing a fresh document. A vector represents the values and their order; it doesn’t store the original quote marks or comment spacing. With a `Document`, the edit targets the sequence itself. Compare the two original items in the input and output above: the two spaces before `# first` stay two spaces, and the single space before `# last` stays one. You can’t pass a quote style to `insert_at`; for a new single-line string, the editor [infers the style from existing strings near the end of the list](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/edit.rs#L3222-L3246).

If you’re editing a file rather than previewing the change, write `doc.to_string()` only after the insertion succeeds. Start by writing to a separate output file so you can review the diff before replacing the original.
