Python
String Conversion
Data Manipulation
List Operations
Programming Tips

How to convert string representation of list to a list

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, the right way to convert a string that looks like a list depends on what format the string actually uses. Some inputs are valid Python literals, some are valid JSON arrays, and some are just comma-separated text that happens to look list-like. The safest solution is to parse according to the real format instead of reaching for eval.

Use ast.literal_eval For Python Literal Syntax

If the string is a valid Python literal such as "[1, 2, 3]" or "['a', 'b']", ast.literal_eval is usually the best answer.

python
1import ast
2
3text = "['apple', 'banana', 'pear']"
4items = ast.literal_eval(text)
5
6print(items)
7print(type(items))

This works because literal_eval can parse safe Python literal structures such as lists, strings, numbers, tuples, dicts, booleans, and None. It does not execute arbitrary code.

Use json.loads For JSON Arrays

If the source string comes from an API or a file that uses JSON, use the JSON parser instead.

python
1import json
2
3text = '["apple", "banana", "pear"]'
4items = json.loads(text)
5
6print(items)
7print(type(items))

This is the correct tool when the input is JSON, but it has JSON rules, not Python rules. For example, JSON uses true, false, and null, while Python literals use True, False, and None.

Do Not Use eval On Untrusted Input

eval can appear to solve the problem quickly:

python
text = "[1, 2, 3]"
items = eval(text)
print(items)

But this is dangerous if the input is not fully trusted, because eval can execute arbitrary Python code instead of just parsing data. That makes it the wrong default for user input, files, HTTP payloads, and logs.

In practice, if you are considering eval, the better question is usually "what format is this string really supposed to be?"

Sometimes The Data Is Not Really A List Literal

A lot of strings only look list-like at first glance. For example:

python
text = "apple,banana,pear"

That is not a Python list literal or a JSON array. It is just comma-separated text, so simple splitting is more appropriate.

python
text = "apple,banana,pear"
items = text.split(",")
print(items)

If whitespace is inconsistent, normalize it:

python
text = "apple, banana, pear"
items = [part.strip() for part in text.split(",")]
print(items)

This is often the cleanest solution for lightweight input formats.

Handle Numeric Lists Carefully

If the input is comma-separated numbers rather than a literal list, convert the split strings into the type you actually need.

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

This is clearer than forcing the data through a parser designed for a different syntax.

A Small Utility Function

If your program receives mixed inputs, write a parser that makes the choice explicit.

python
1import ast
2import json
3
4
5def parse_list_string(text):
6    text = text.strip()
7
8    if text.startswith("[") and text.endswith("]"):
9        try:
10            return json.loads(text)
11        except json.JSONDecodeError:
12            return ast.literal_eval(text)
13
14    return [part.strip() for part in text.split(",") if part.strip()]
15
16
17print(parse_list_string('["a", "b"]'))
18print(parse_list_string("['x', 'y']"))
19print(parse_list_string("one, two, three"))

This keeps the parsing rules visible instead of hiding them in an unsafe shortcut.

Choose The Parser Based On The Source

A useful rule of thumb is:

  • use json.loads for JSON,
  • use ast.literal_eval for trusted Python-literal text,
  • use split for simple delimiter-based strings.

That small distinction prevents a lot of avoidable bugs.

Common Pitfalls

  • Using eval on untrusted input because it seems convenient.
  • Passing Python-style strings into json.loads and expecting them to parse.
  • Using ast.literal_eval when the input is really just comma-separated text.
  • Forgetting to strip whitespace after splitting delimiter-based data.
  • Converting to a list successfully but leaving elements as strings when numbers were needed.

Summary

  • Use ast.literal_eval for strings that contain Python list literals.
  • Use json.loads when the input is valid JSON.
  • Use string splitting for simple delimiter-based formats.
  • Avoid eval unless you completely control the input and understand the risk.
  • The correct parser depends on the real format of the string, not on how list-like it appears.

Course illustration
Course illustration

All Rights Reserved.