How to convert a str to a single element list in python

Just put square brackets

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

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]

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

Tags:

Python