Skip to content

YAML – Sequence Styles

In YAML, a sequence is an ordered collection of items, analogous to lists or arrays in programming languages. YAML provides two main styles for representing sequences: block style and flow style. Understanding these styles is crucial for writing readable and well-structured YAML documents.

Collections in YAML are typically indexed by sequential integers starting from zero, similar to arrays. Sequences are a fundamental type of collection.

Block style sequences are more verbose and often more readable for longer lists. Each item in a block sequence starts with a hyphen and a space (- ) at the beginning of a new line. All items in the sequence must share the same indentation level.

# Block style sequence of planets
planets:
- Mercury
- Venus
- Earth
- Mars

Flow style sequences are more compact and are written inline, enclosed in square brackets ([]). Items are separated by a comma and a space (, ). Flow style is suitable for short lists or when embedding a list within another structure where block style might be cumbersome.

# Flow style sequence of planets
planets_flow: [Mercury, Venus, Earth, Mars]

Example: Combining Styles and Explicit Tagging

Section titled “Example: Combining Styles and Explicit Tagging”

The following example demonstrates both block and flow style sequences, along with explicit tagging (!!seq) to denote a sequence. While explicit tagging is often not necessary for standard sequences (as YAML parsers usually infer the type), it can be useful for clarity or specific schema requirements.

# Example demonstrating different sequence styles
# Ordered sequence of nodes in Block Style
rocky_planets: !!seq
- Mercury # Innermost planet
- Venus # Earth's "sister" planet
- Earth # Our home
- Mars # The Red Planet
# Ordered sequence of nodes in Flow Style
gas_giants: !!seq [Jupiter, Saturn, Uranus, Neptune] # Outer planets
ice_dwarfs_flow:
- Pluto
- Eris
- Haumea

When parsed, this YAML would result in a data structure conceptually similar to the following JSON:

{
"rocky_planets": [
"Mercury",
"Venus",
"Earth",
"Mars"
],
"gas_giants": [
"Jupiter",
"Saturn",
"Uranus",
"Neptune"
],
"ice_dwarfs_flow": [
"Pluto",
"Eris",
"Haumea"
]
}

Choosing between block and flow style often depends on readability and context. Block style is generally preferred for top-level sequences or lists with many items, while flow style can be convenient for short, embedded sequences.