Splitting String to List of Characters Python (original) (raw)
Last Updated : 04 Feb, 2025
The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. **For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'].
Using list comprehension
List comprehension is a efficient way to create a new list by iterating over an iterable .When splitting a string into characters, list comprehension is particularly useful due to its clean syntax and fast performance .
Python `
s = "GeeksforGeeks"
res = [char for char in s] print(res)
`
Output
['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's']
**Explanation: list comprehension iterate over each character in the string **s, creating a new list where each character from the string is added as an individual element.
Using list()
list() constructor convert any iterable into a list. By passing a string to list(), it efficiently breaks the string into its individual characters, making it one of the simplest and most efficient ways to split a string into a list.
Python `
s = "GeeksforGeeks"
res = list(s) print(res)
`
Output
['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's']
**Explanation: list() convert the string s into a list, where each character from the string becomes an individual element in the list.
Using map()
map() applies a given function to each item of an iterable and returns an iterator. While map() can be used for more complex transformations, it's also a good option for splitting a string into characters when combined with the str() function.
Python `
s = "GeeksforGeeks"
res = list(map(str, s)) print(res)
`
Output
['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's']
**Explanation: map()
apply the **str
**function to each character of the string s
, then converts the result into a list.
Using for loop
For loop is a traditional approach where we iterate over each character in the string and append it to a list. This method is more manual but can be used effectively, especially when we need to add additional logic inside the loop.
Python `
s = "GeeksforGeeks" res = []
for char in s: res.append(char) print(res)
`
Output
['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's']
**Explanation: for loop iterates over each character in the string **s and appends it to the list res. After the loop, the list res contains the individual characters of the string.