How to convert string representation of list to a list
You can use the ast.literal_eval() function from the ast module to safely evaluate a string and convert it to a list.
You can use the ast.literal_eval() function from the ast module to safely evaluate a string and convert it to a list. Here's an example:
Convert string representation of list to a list in Python
import ast
string_representation = "[1, 2, 3, 4, 5]"
list_from_string = ast.literal_eval(string_representation)
print(list_from_string) # Output: [1, 2, 3, 4, 5]
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
This method is safe for untrusted input because ast.literal_eval() only parses Python literals and does not execute arbitrary code.