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.
CommaSeparatedListOutputParser in 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.
parser.parse("")parser.parse("apple")parser.parse("apple, banana, cherry")parser.parse(" apple , banana ,cherry ")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.
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}")
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.
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.