Explain Codes LogoExplain Codes Logo

How to convert a string with comma-delimited items to a list in Python?

python
list-comprehension
string-manipulation
data-types
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

To convert a comma-separated string to a list, use the split():

items = "apple,banana,cherry" list_items = items.split(",") # Result: ['apple', 'banana', 'cherry']

If your string uses other characters or patterns as separators, set them as delimiter in split().

Dealing with whitespace in your string

split() method is your friend when dealing with a comma-delimited string. However, beware of spaces before or after commas. For inconsistent white spaces, clean up your string first using strip() or a list comprehension.

items = "apple, banana , cherry" # Using list comprehension to wield the mighty broomstick clean_list = [item.strip() for item in items.split(',')] # Result: ['apple', 'banana', 'cherry']

The above line of code ensures the items in your list are as clean as whistleblowers.

Accessing list elements and converting back to strings

Your newly-formed list allows access to individual elements via indexes. Remember, in Python, indexes count from 0, not 1 - just like the hours in a day!

# Accessing the first item in the list first_item = list_items[0] # 'apple', not 'banana'!

Also, if you ever need to reunite your list items back into a string, join() is your man (or method).

rejoined = ','.join(list_items) # Result: "apple,banana,cherry"

Complex strings that counterfeit lists

In cases where you have a string pretending to be a list (like "[1, 2, 3]"), use the ast.literal_eval method. Acting as a bouncer, this method only processes Python literals, keeping you safe from malicious inputs.

import ast str_list = "[1, 2, 3]" actual_list = ast.literal_eval(str_list) # Result: [1, 2, 3]

Note: Ensure your string is dressed up exactly like a list before ast.literal_eval can let it into the list club, or you will get a ValueError.

Fine tuning: Delimiters, data types and nested structures

Delimiter options besides commas

Delimiters are not restricted to commas. A string might use semicolons, pipe characters, or even whitespace. Adjust split() to your delimiter of choice accordingly.

# Semi-colonized string items_semicolon = "apple;banana;cherry" list_items = items_semicolon.split(";")

Data type conversion

To split() all items are just strings. To convert them to numerical types, enter the world of map function:

number_string = "1,2,3" number_list = list(map(int, number_string.split(','))) # Result: [1, 2, 3]

Preserving structure and types for complex strings

For strings containing nested structures like lists or tuples, the classic tool from the chest, ast.literal_eval, comes to the rescue, maintaining the hierarchical structure.