I have a str variable: var_1 = "hello" , and I want to convert it to a single element list, I try this:

>>> list(var_1)
['h', 'e', 'l', 'l', 'o']

which is not the ['hello'] that I want.

How do I do that?

Just put square brackets

>>> var_1 = "hello"
>>> [var_1]

Does var1 = [var1] accomplish what you’re looking for?

Just do the following:

var_1 = ['hello']

It can be useful to add a check before doing so, as such:

if not isinstance(var_1, list): var_1 = [var_1]

A use case for this code is in functions that can take either a string or a list of strings and want the functions to handle that silently. E.g.:

def dataframe_key_columns(dataframe, keys):
    if not isinstance(keys, list): keys = [keys]
    return [dataframe[key] for key in keys]

Let me provide you a much easier and authentic way to do it.


You will get a list with ‘hello’ as its element.
And you can use the list L anyway you like.