Skip to main content
How to convert string to list in python

How to convert string to list in python

This tutorial help to convert string to python list. We will discuss different ways to convert a string to a list in Python. The Strings and lists are the most used python objects.

I have earlier shared python tutorial Python List to String.Here, We are going to learn how we can convert a string into a list in Python.

Convert String to List Using List() in Python

A list can be made from an existing iterable object using the list() function. The input argument for the list() function is an iterable object. It returns a list with every element of the iterable object is returned.

myStr = "pythonpip"
output_list = list(myStr)
print("The input string is:", myStr)
print("The output list is:", output_list)

Output:

The input string is: pythonpip
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'p', 'i', 'p']

The above code has returned the list of characters in the string.

String to List Using append() Method in Python

An element can be added to a list using the append() method. The function takes an element as its input parameter and appends it to the list when it is called on a list.

my_str = "pythonpip"
my_list = []
for character in my_str:
my_list.append(character)
print("The input string is:", my_str)
print("The output list is:", my_list)

Output:

The input string is: pythonpip
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'p', 'i', 'p']

The above code:

First we have created an empty list named my_list to store the output list. then, iterate through the characters of the input string using a for loop. Finally, append the current character to my_list using the append() method.

String to List Using extend()

The extend() method is used to add several elements to a list at the same time.

We’ll follow the following steps to convert string to list:

  • We will first create an empty list named my_list.
  • Then, We’ll invoke the extend() method on my_list with the input string as an input argument to the extend() method.
myStr = "pythonpip"
myList = []
myList.extend(myStr)
print("The input string is:", myStr)
print("The output list is:", myList)

Output:

The input string is: pythonpip
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'p', 'i', 'p']

Conclusion

In this article, we covered different Python methods for converting strings to lists. You can try to use one of them which suits your code and solves your purpose as well as meets up to your requirements.

Questions in the comments are appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *