What you want to do is evaluate (eval
) some code so it gets resolved by the interpreter. Since you cannot eval
lists, you have to put the square brackets in the string, so it gets evaluated:
l = '[1, 2, 3, 4, 5]'
eval(l)
>>> [1, 2, 3, 4, 5]
Explanation:
Your first "list" is an object whose type is not a list
, but a string (str
).
list = '1, 2, 3, 4, 5'
type(list)
>>> str
By the way, I highly encourage you not to use python keywords such as 'list' as variable names
When you put square brackets around, you're defining a list with a single object, which is this string object:
format = [list]
type(format)
>>> list
len(format) # How many elements does it have?
>>> 1
So what you actually want to do is to define this list in a string manner and evaluate it:
l = '[1, 2, 3, 4, 5]'
eval(l)
>>> [1, 2, 3, 4, 5]