How to Convert a Comma-Delimited String to a List in Python
Converting a comma-separated string into a list is one of the most common string-processing tasks in Python. You'll encounter this when parsing CSV data, handling user input, reading configuration values, processing query parameters, or splitting tags and categories.
In this guide, you'll learn multiple methods to convert a comma-delimited string to a list in Python, handle edge cases like whitespace and empty values, and choose the right approach for your use case.
Using str.split() (Recommended)β
The split() method is the most straightforward and efficient way to convert a comma-delimited string to a list. It divides the string at each occurrence of the specified delimiter and returns a list of substrings.
s = "apple,banana,cherry,date"
result = s.split(',')
print(result)
Output:
['apple', 'banana', 'cherry', 'date']
This works cleanly when the string has no extra spaces around the commas.
Handling Whitespace with split() and strip()β
Real-world data often includes spaces after commas. The basic split(',') preserves those spaces:
s = "apple, banana, cherry, date"
# Without stripping: spaces are included
result = s.split(',')
print(result)
Output:
['apple', ' banana', ' cherry', ' date']
Notice the leading spaces on ' banana', ' cherry', and ' date'. To remove them, combine split() with strip() using a list comprehension:
s = "apple, banana, cherry, date"
result = [item.strip() for item in s.split(',')]
print(result)
Output:
['apple', 'banana', 'cherry', 'date']
The split() + strip() combination is the most reliable approach for real-world data. Always use it when the input might contain inconsistent spacing:
s = " apple ,banana , cherry , date "
result = [item.strip() for item in s.split(',')]
print(result) # ['apple', 'banana', 'cherry', 'date']
Using split() Without Arguments for Flexible Splittingβ
When called without arguments, split() splits on any whitespace (spaces, tabs, newlines) and automatically handles multiple consecutive spaces. However, this doesn't work for comma-delimited strings unless you replace commas first:
s = "apple, banana, cherry, date"
# Replace commas with spaces, then split on whitespace
result = s.replace(',', ' ').split()
print(result)
Output:
['apple', 'banana', 'cherry', 'date']
Using re.split() for Complex Delimitersβ
When the delimiter pattern is more complex, such as commas optionally followed by spaces, or multiple delimiter types, use re.split() from the re module:
import re
s = "apple, banana, cherry,date, elderberry"
# Split on comma followed by any amount of whitespace
result = re.split(r',\s*', s)
print(result)
Output:
['apple', 'banana', 'cherry', 'date', 'elderberry']
The pattern r',\s*' matches a comma followed by zero or more whitespace characters, handling all spacing variations in a single operation.
Splitting on Multiple Delimitersβ
import re
s = "apple,banana;cherry|date grape"
# Split on comma, semicolon, pipe, or space
result = re.split(r'[,;|\s]+', s)
print(result)
Output:
['apple', 'banana', 'cherry', 'date', 'grape']
Converting to Specific Data Typesβ
Often the comma-separated values represent numbers, not just strings. Use map() or list comprehension to convert types during splitting:
Converting to Integersβ
s = "10, 20, 30, 40, 50"
result = [int(x.strip()) for x in s.split(',')]
print(result)
print(type(result[0]))
Output:
[10, 20, 30, 40, 50]
<class 'int'>
Using map() for Type Conversionβ
s = "1.5, 2.7, 3.14, 4.0"
result = list(map(float, s.split(',')))
print(result)
Output:
[1.5, 2.7, 3.14, 4.0]
int()When converting comma-separated numbers to integers, you do not need to strip spaces manually.
Pythonβs int() function automatically ignores leading and trailing whitespace.
s = "10, 20, 30"
result = list(map(int, s.split(',')))
print(result)
Output:
[10, 20, 30]
This works because:
int(" 20") # β
Valid
int("20 ") # β
Valid
int("\n20") # β
Valid
You only need .strip() if the string may contain non-numeric characters or unexpected formatting.
Handling Edge Casesβ
Empty Strings Between Commasβ
When there are consecutive commas, split(',') produces empty strings:
s = "apple,,banana,,,cherry"
result = s.split(',')
print(result)
Output:
['apple', '', 'banana', '', '', 'cherry']
To filter out empty values:
s = "apple,,banana,,,cherry"
result = [item for item in s.split(',') if item]
print(result)
Output:
['apple', 'banana', 'cherry']
Empty Input Stringβ
s = ""
result = s.split(',')
print(result)
print(len(result))
Output:
['']
1
Splitting an empty string produces a list with one empty string, not an empty list. Handle this explicitly if needed:
s = ""
result = [item for item in s.split(',') if item.strip()]
print(result) # []
Single Value (No Commas)β
s = "apple"
result = s.split(',')
print(result)
Output:
['apple']
This correctly returns a single-element list.
Using the csv Module for Quoted Valuesβ
When comma-separated values contain commas within quoted strings, the simple split(',') approach breaks down. Use Python's csv module for proper parsing:
import csv
import io
s = 'Alice,"Smith, Jr.",30,"New York, NY"'
reader = csv.reader(io.StringIO(s))
result = next(reader)
print(result)
Output:
['Alice', 'Smith, Jr.', '30', 'New York, NY']
The csv module correctly handles quoted fields containing commas, which split(',') cannot do:
# β Wrong: split breaks quoted fields
print(s.split(','))
# ['Alice', '"Smith', ' Jr."', '30', '"New York', ' NY"']
Practical Example: Parsing Configuration Valuesβ
config_line = "allowed_hosts = localhost, 127.0.0.1, example.com, *.example.org"
# Extract the value part
key, value = config_line.split('=', 1)
# Parse the comma-separated hosts
hosts = [host.strip() for host in value.split(',')]
print(f"Key: {key.strip()}")
print(f"Hosts: {hosts}")
Output:
Key: allowed_hosts
Hosts: ['localhost', '127.0.0.1', 'example.com', '*.example.org']
Quick Comparison of Methodsβ
| Method | Handles Spaces | Handles Quotes | Type Conversion | Best For |
|---|---|---|---|---|
s.split(',') | β | β | β | Clean, simple strings |
split(',') + strip() | β | β | β | Most real-world data |
re.split(r',\s*', s) | β | β | β | Complex/multiple delimiters |
map(int, s.split(',')) | β | β | β | Numeric strings (no spaces) |
| List comprehension | β | β | β | Full control, filtering |
csv.reader() | β | β | β | Quoted CSV fields |
Conclusionβ
Converting a comma-delimited string to a list in Python is straightforward, but choosing the right method depends on your data:
- Use
split(',')for clean strings without extra whitespace. It's the simplest and fastest option. - Use
split(',')withstrip()in a list comprehension for real-world data that may contain inconsistent spacing. This is the most commonly needed approach. - Use
re.split()when dealing with complex or multiple delimiters. - Use
map()or list comprehension with type conversion when values represent numbers. - Use the
csvmodule when values may contain commas within quoted fields.
For most everyday use cases, [item.strip() for item in s.split(',')] provides the best combination of simplicity and reliability.