Convert String to List in Python

Converting a string to a list in Python can mean several different things. You may want to split comma-separated text into items, turn every character into its own element, parse a JSON array, or convert text numbers into numeric values.

The official Python documentation covers str.split(), list(), json.loads(), and ast.literal_eval().

Start by identifying the format of the string. Plain delimited text should usually use split(). A string that already contains JSON should use json.loads(). A Python literal from a trusted source can use ast.literal_eval(). Do not use eval() for this job.

Also decide whether whitespace, empty items, and type conversion should happen during the conversion. Cleaning those details near the split step makes the resulting list easier to trust later.

Be careful with strings that only look like lists. The text "red,blue", the JSON text ["red","blue"], and the Python literal text ['red', 'blue'] need different tools. Matching the tool to the format prevents brittle cleanup code.

For production data, keep the conversion step small and testable. Convert the string, validate the list length or item types, and then pass the clean list to the next part of the program.

Split A Comma-Separated String

Use split(",") when the string uses commas between items.

text = "red,blue,green"
items = text.split(",")

print(items)
print(len(items))

The separator is not included in the output. The result is a list of strings in the same order as the original text.

This pattern works for simple values such as tags, labels, colors, and short configuration fields. For real CSV files with quoted commas, use the csv module instead.

If the separator can be a pipe, tab, semicolon, or newline, pass that separator explicitly. Relying on the default whitespace split is useful for words, but it is not the same as splitting structured delimited text.

Clean Spaces And Empty Items

Imported text often contains extra spaces or empty entries. A list comprehension can strip each part and keep only non-empty strings.

text = " apple, , banana, cherry , "
items = [part.strip() for part in text.split(",") if part.strip()]

print(items)

This produces a cleaner list without blank strings. It is useful for form fields, tag inputs, and small admin settings.

If blank values should be reported as validation errors, collect their positions instead of silently removing them.

That choice depends on the workflow. A search filter may ignore blanks safely, while an imported row may need to keep blanks so the user can fix the original data.

Convert A String To Characters

Use list(text) when each character should become an element.

word = "Python"
characters = list(word)

print(characters)
print(characters[0])

This does not split on words or separators. It walks through the string and places each character in the list.

Use this for character-level tasks such as simple counters, puzzles, token checks, or examples that demonstrate sequence behavior.

Do not use list(text) when you want words. It does not understand spaces as word separators; it simply returns every character in order.

Convert Text Numbers To Integers

After splitting numeric text, convert each item with int() or another appropriate function.

text = "10, 20, 30"
numbers = [int(part.strip()) for part in text.split(",")]

print(numbers)
print(sum(numbers))

The result is a list of integers, not strings. If any part is not a valid integer, int() raises ValueError.

For user-entered data, catch that error or validate the parts before converting. A helpful error message should point to the item that failed.

When the values can be decimal numbers, use float() or decimal.Decimal instead of int(). The list conversion pattern stays the same; only the item conversion changes.

Parse A JSON Array String

Use json.loads() when the string is valid JSON.

import json

text = '["red", "blue", "green"]'
items = json.loads(text)

print(items)
print(type(items))

This is the right choice for API responses, stored JSON settings, and structured text that uses JSON syntax.

JSON strings must use double quotes around string values. If the input is not valid JSON, json.loads() raises json.JSONDecodeError.

Parse A Trusted Python Literal

If a trusted string contains Python list syntax, use ast.literal_eval(). It parses literal data without running arbitrary code.

import ast

text = "['red', 'blue', 'green']"
items = ast.literal_eval(text)

print(items)
print(isinstance(items, list))

This can handle Python-style single quotes, tuples, numbers, dictionaries, and lists. It should still be used only when the expected format is a Python literal.

After parsing, verify that the result is actually a list if the rest of the program expects one. Literal parsers can return a dictionary, tuple, number, or string depending on the input.

The practical rule is simple: use split() for delimited text, list() for characters, json.loads() for JSON arrays, and ast.literal_eval() for trusted Python literal text.

Good tests should include an empty string, one item, spaces around separators, repeated separators, invalid numbers, and malformed JSON. Those cases make the conversion rule explicit and prevent quiet data loss.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
em.willowy
em.willowy
4 years ago

Thank you! I’d been struggling all morning to find solution #6.

Simbha
Simbha
4 years ago

Thank you very much… Method-7 was very handy.
I had to convert a string which actually had a set of dictionaries as list elements. However, the ast.literal_eval(str) converted it to a tuple. I have to use additional statement like list(ast.literal_eval(str) ) to make it a list.