How To Convert A String To A List In Python

In this tutorial, we will discuss how to convert a string to a list in Python. Converting a string to a list is a common operation in Python programming and is often needed when we want to perform operations on individual characters or substrings.

Python provides various methods to achieve this conversion. We will learn different ways of converting a string into a list so that you can choose the one that fits best for your use case.

Method 1: Using the list() function

The easiest method to convert a string to a list is by using the built-in list() function. The list() function takes an iterable (like a string) as its argument and returns a list containing individual elements (characters) of the iterable.

Output:

Converted list: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

Method 2: Using list comprehension

List comprehension is a concise way to create a list from any iterable. In this case, we can use list comprehension to convert a string to a list, where each element of the list is a character from the string.

Output:

Converted list: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

Method 3: Using the split() method

The split() method is used to split a string into a list of substrings based on a specified delimiter. If no delimiter is provided, Python will automatically use whitespace (space, tab, newline, etc.) as the delimiter.

Output:

Converted list: ['Hello,', 'World!']

In the example above, the string was split into a list of words using spaces as the delimiter. You can specify any delimiter in the split() method to achieve the desired result.

Method 4: Using split() and list() together

In some cases, it might be better to split a string into words and then convert each word into a list of characters. This can be achieved using a combination of the split() method and the list() function.

Output:

Converted list: [['H', 'e', 'l', 'l', 'o', ','], ['W', 'o', 'r', 'l', 'd', '!']]

In this example, the input_string is first split into words using the split() method, and then each word is converted into a list of characters using the list() function.

Full Code:

Output:

Converted list using method 1: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
Converted list using method 2: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
Converted list using method 3: ['Hello,', 'World!']
Converted list using method 4: [['H', 'e', 'l', 'l', 'o', ','], ['W', 'o', 'r', 'l', 'd', '!']]

Conclusion

In this tutorial, we have learned different methods to convert a string to a list in Python. Depending on the specific requirements of your application, you can choose the most suitable method from the listed options. These methods offer a simple and efficient way to work with strings and lists in Python.