Open In App

Convert string to a list in Python

Last Updated : 16 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, converting a string to a list can be essential for handling text processing tasks. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we’ll explore these conversion techniques with simple examples.

The most common ways to convert a string into a list is by using the split() method.

Using the split() Method

The split() method by default splits a string based on spaces, but it can also split using a custom delimiter.

Example 1: Splitting a string by space

s = "Geeks for Geeks"

# Splits string into words based on space
a = s.split()
print(a)

Output
['Geeks', 'for', 'Geeks']

Explanation: The split() method splits the string into words based on spaces.

Example 2: Splitting a string by comma (,)

s = "Geeks,for,Geeks"

# Splits string into words based on comma (,).
a = s.split(',')
print(a)

Output
['Geeks', 'for', 'Geeks']

Using list()

If we want to break down a string into list of individual characters then we can use list() function which is a simple and effective method. This approach adds each character of the string as an element in a list.

s = "Geeks for Geeks"

# adds each character of string 
# as an element in a list
a = list(s)
print(a)

Output
['G', 'e', 'e', 'k', 's', ' ', 'f', 'o', 'r', ' ', 'G', 'e', 'e', 'k', 's']

Explanation: The list(s) function takes every character in the string s and places it as an element in the list.

Using list comprehension

List comprehension can be used for converting a string into list of individual characters. This approach is particularly useful if we want to manipulate each character before adding it to the list. While a loop can also achieve the same result but list comprehension provides better readability and conciseness.

s = "Geeks for Geeks"
a = [ch for ch in s]
print(a)

Output
['G', 'e', 'e', 'k', 's', ' ', 'f', 'o', 'r', ' ', 'G', 'e', 'e', 'k', 's']

Related Articles:



Next Article

Similar Reads

three90RightbarBannerImg