Given a string, the task is to convert it into a list. Depending on the requirement, we can convert the string into a list of characters, words, or values separated by a specific delimiter. For Example:
Input: text = "Python is easy"
Output: ['Python', 'is', 'easy']
Now, let's explore different methods to convert a string into a list in Python.
Using split()
split() method converts a string into a list by splitting it at a specified separator. If no separator is provided, it splits the string wherever it finds whitespace.
s = "Python programming language"
a = s.split()
print(a)
Output
['Python', 'programming', 'language']
Explanation: Since no separator is specified, split() separates the string at spaces and returns a list containing each word.
Using list()
list() function converts a string into a list by treating every character as a separate element. This includes letters, digits, punctuation marks, and even spaces.
s = "Python"
a = list(s)
print(a)
Output
['P', 'y', 't', 'h', 'o', 'n']
Explanation: list() function iterates through the string and adds each character as an individual element in the list.
Using List Comprehension
List comprehension iterates through the string and creates a list of characters. It is useful when each character needs to be processed before storing it in the list.
s = "Python"
a = [ch for ch in s]
print(a)
Output
['P', 'y', 't', 'h', 'o', 'n']
Explanation: expression iterates through every character in the string and stores each one as a separate element in the resulting list.
Using split() with a Custom Delimiter
split() method also allows splitting a string using a custom separator instead of spaces. This is useful for comma-separated values, hyphen-separated text, and similar formats.
s = "Python,Java,C++"
a = s.split(",")
print(a)
Output
['Python', 'Java', 'C++']
Explanation: string is split wherever a comma appears, producing a list in which each programming language becomes a separate element.