0
0
LangChainframework~5 mins

CommaSeparatedListOutputParser in LangChain

Choose your learning style9 modes available
Introduction

The CommaSeparatedListOutputParser helps turn a string of items separated by commas into a list you can use in your program. It makes it easy to work with simple lists from text.

When you get a response from a language model that lists items separated by commas.
When you want to convert a simple text list into a Python list for easier processing.
When you need to parse user input that is typed as comma-separated values.
When you want to cleanly extract multiple answers from a single string output.
Syntax
LangChain
from langchain.output_parsers import CommaSeparatedListOutputParser

parser = CommaSeparatedListOutputParser()

# To parse a comma separated string:
result_list = parser.parse("apple, banana, cherry")

The parser splits the string by commas and trims spaces around items.

It returns a Python list of strings.

Examples
Returns an empty list if the input string is empty.
LangChain
parser.parse("")
Returns a list with one item: ['apple'].
LangChain
parser.parse("apple")
Returns a list with three items: ['apple', 'banana', 'cherry'].
LangChain
parser.parse("apple, banana, cherry")
Returns trimmed items: ['apple', 'banana', 'cherry'].
LangChain
parser.parse("  apple ,  banana ,cherry  ")
Sample Program

This program shows how to use the CommaSeparatedListOutputParser to convert a comma-separated string into a Python list. It prints the original string and the resulting list.

LangChain
from langchain.output_parsers import CommaSeparatedListOutputParser

# Create the parser
parser = CommaSeparatedListOutputParser()

# Example input string from a language model
input_string = "red, green, blue, yellow"

# Parse the string into a list
parsed_list = parser.parse(input_string)

# Print before and after
print(f"Input string: '{input_string}'")
print(f"Parsed list: {parsed_list}")
OutputSuccess
Important Notes

The parsing operation runs in linear time relative to the length of the string.

It uses extra space proportional to the number of items parsed.

A common mistake is to forget trimming spaces, but this parser handles that automatically.

Use this parser when your output is a simple comma-separated list. For more complex formats, consider other parsers.

Summary

The CommaSeparatedListOutputParser converts comma-separated text into a list.

It trims spaces and handles empty or single-item inputs gracefully.

It is useful for parsing simple lists from language model outputs or user input.