How to convert string representation of list to a list in Python?

To convert a string representation of a list (e.g., "[1, 2, 'apple']") into an actual Python list, you can use ast.literal_eval() (recommended for safety) or eval() (use with caution). Here’s a detailed guide with examples:

1. Using ast.literal_eval (Safe Method)

The ast (Abstract Syntax Tree) module’s literal_eval() safely parses strings containing Python literals (lists, dicts, numbers, strings, etc.) and is immune to code injection attacks.

Example:

import ast

string_list = "[1, 2, 'apple', [3, 4], {'key': 'value'}]"

# Convert the string to a list
parsed_list = ast.literal_eval(string_list)

print(parsed_list)        # Output: [1, 2, 'apple', [3, 4], {'key': 'value'}]
print(type(parsed_list))  # Output: <class 'list'>

Key Features:

  • Handles nested lists, dictionaries, and mixed data types.
  • Raises SyntaxError for malformed strings.
  • Safe for untrusted input (unlike eval()).

2. Using eval() (Unsafe, Use with Caution)

The eval() function executes any string as Python code, which can be dangerous if the input is untrusted.

Example:

string_list = "[1, 2, 'apple']"

# Convert the string to a list
parsed_list = eval(string_list)

print(parsed_list)        # Output: [1, 2, 'apple']
print(type(parsed_list))  # Output: <class 'list'>

Risks:

  • Security Vulnerability: Executes arbitrary code (e.g., "__import__('os').system('rm -rf /')").
  • Only use for trusted input.

3. Handling Edge Cases

Case 1: Invalid String

import ast

invalid_string = "[1, 2, 'unclosed quote]"

try:
    parsed_list = ast.literal_eval(invalid_string)
except SyntaxError as e:
    print(f"Error: {e}")  # Output: Error: unterminated string literal

Case 2: JSON-like Strings

For strings formatted as JSON (double quotes only), use json.loads():

import json

json_string = '[1, 2, "apple"]'  # JSON requires double quotes
parsed_list = json.loads(json_string)

print(parsed_list)  # Output: [1, 2, 'apple']

4. Custom Parsing (For Simple Cases)

For basic lists without nested structures, use string manipulation:

string_list = "[1, 2, 'apple']"

# Remove brackets and split elements
cleaned = string_list.strip('[]').split(', ')

# Convert elements to appropriate types (example for integers/strings)
parsed_list = []
for item in cleaned:
    item = item.strip("'\"")  # Remove quotes
    if item.isdigit():
        parsed_list.append(int(item))
    else:
        parsed_list.append(item)

print(parsed_list)  # Output: [1, 2, 'apple']

Summary

MethodUse CaseSafety
ast.literal_eval()General-purpose, nested structuresSafe ✅
eval()Trusted input onlyRisky ❌
json.loads()JSON-formatted strings (double quotes)Safe ✅
Custom ParsingSimple, flat listsDepends on code

Full Example with ast.literal_eval

import ast

def string_to_list(s):
    try:
        return ast.literal_eval(s)
    except (SyntaxError, ValueError) as e:
        print(f"Failed to parse: {e}")
        return []

# Example usage:
input_string = "[1, 2, 'apple', [3, 4]]"
result = string_to_list(input_string)
print(result)  # Output: [1, 2, 'apple', [3, 4]]

Key Notes

  • Always validate input before parsing.
  • Prefer ast.literal_eval() over eval() for security.
  • Use json.loads() for JSON-compliant strings.

Leave a Reply

Your email address will not be published. Required fields are marked *