Skip to content
Advertisement

How to extract a list from a string in a list in python

I read a list of lists from a txt file and I got a list like this:

["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]

Each list item in this list is a str type which is a problem.

it should be like this:

[[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793], [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]]

How do I do that?

Advertisement

Answer

Using the eval() function along with a list comprehension we can try:

inp = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]
output = [eval(x) for x in inp]
print(output)

This prints:

[
    [21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793],
    [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]
]
Advertisement