How to Create a List in YAML
YAML (YAML Ain't Markup Language) provides a simple and intuitive way to create lists. Lists in YAML can be defined using a dash (-
) followed by a space before each item in the list. This structure allows for easy representation of ordered collections of items.
Basic Syntax for Lists
The basic syntax for creating a list in YAML is as follows:
list_name:
- item1
- item2
- item3
In this example, list_name
is the key that represents the list, and item1
, item2
, and item3
are the individual items in the list.
Example of a Simple List
Here is a simple example of a list representing a collection of fruits:
fruits:
- Apple
- Banana
- Cherry
- Date
In this example, fruits
is the key, and it contains a list of fruit names: Apple
, Banana
, Cherry
, and Date
.
Lists with Mixed Data Types
YAML lists can contain items of different data types, including strings, numbers, and even other lists or dictionaries. Here’s an example of a list that includes various data types:
mixed_list:
- "Hello"
- 42
- true
-
- Subitem1
- Subitem2
In this example, mixed_list
contains a string, a number, a boolean, and another list with two subitems.
Nested Lists
YAML also allows for nested lists, where a list can contain other lists. This is useful for representing more complex data structures. Here’s an example:
courses:
- name: Mathematics
topics:
- Algebra
- Geometry
- Calculus
- name: Science
topics:
- Physics
- Chemistry
In this example, courses
is a list of dictionaries, where each dictionary represents a course with a name
and a nested list of topics
.
Conclusion
In summary, creating a list in YAML is straightforward and involves using dashes to denote each item. The ability to nest lists and include various data types makes YAML a flexible choice for representing structured data.