We can use the constructor to convert string to list of characters in Python.
To convert string to list of characters in Python:
-
Use the
list()
function.
See the code below.
# Convert string to list of characters in Python string = "educatepython" # Use the list() function to convert string to list of characters converted_list = list(string) print(converted_list) # Output: ['e', 'd', 'u', 'c', 'a', 't', 'e', 'p', 'y', 't', 'h', 'o', 'n']
This is the most direct and efficient method to convert a string to a list of characters in Python.
Similarly, we can use the
To convert string to list of characters in Python:
-
Use the
extend()
function.
See the code below.
# Convert string to list of characters in Python string = "educatepython" # Use the extend() function to convert string to list of characters converted_list = [] converted_list.extend(string) print(converted_list) # Output: ['e', 'd', 'u', 'c', 'a', 't', 'e', 'p', 'y', 't', 'h', 'o', 'n']
Alternatively, we can also follow a traditional approach of using the for
loop. We will use list comprehension to create a list in a single line of code using the for
loop.
To convert string to list of characters in Python:
-
Use the
for
loop to iterate over a list. -
Append each character using list comprehension.
See the code below.
# Convert string to list of characters in Python string = "educatepython" # Use the for loop to convert string to list of characters converted_list = [a for a in string] print(converted_list) # Output: ['e', 'd', 'u', 'c', 'a', 't', 'e', 'p', 'y', 't', 'h', 'o', 'n']
To conclude
This tutorial demonstrated different methods to convert string to a list of characters in Python. The list()
achieves this directly. The extend()
function appends a string to an empty list as characters. Finally, the for
loop can iterate over a list and add the elements individually.
Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.