Convert a string to Array (List) in Python(3 ways)

📋 Table Of Content
In this article, we will learn how we can convert a given string into an array using python.
In Python, there is no data type called as an Array. Python uses a List that can hold multiple data types in a single variable.
So here we will see how to convert a string into a Python List.
Convert String to List in Python
There are three different ways by which we can convert a string into a list in python.
- Using split() method
- Using list() function
- Using list comprehensions
Let's see some examples to understand it better.
Convert a String to an Array using split() method
In python, the split()
method converts a string into a list. It splits the string by the specified separator.
Syntax:
String.split(separator. maxSplit)
The separator
is the delimiter at which the string gets split. By default the separator is whitespace.
And the maxSplit
tells the split() method how many times we want the given string to be split.
Example:
str = 'Hello how are you'
arr_list = str.split()
print(arr_list)
Output:
['Hello', 'how', 'are', 'you']
In this example, we called the split()
method on the string to convert it into an array.
And since we have not specified the separator to the split()
method, it split the string by the whitespaces.
Convert a string into an array using list() function.
The list()
is an in-built python function that is used to create a list.
To convert a given string into a list, we need to pass the string as an argument to the list function. It will convert the string and return to us a list containing the characters of the string.
Example:
str = 'Hello'
arr = list(str)
print(arr)
Output:
['H', 'e', 'l', 'l', 'o']
Here, we have converted the string into a list by using the list
function.
It is important to note that, in list()
function even the whitespaces are considered as characters. For example:
str = 'Hello world '
arr = list(str)
print(arr)
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ']
As you can see the spaces between the words are considered as a character and it returned as list elements in the form of an empty string.
Convert a string to array using list comprehensions
We can use list comprehensions to convert a string into a python list.
Example:
str = "hello"
arr = [c for c in str]
print(arr)
Output:
['h', 'e', 'l', 'l', 'o']
You can check the type of the output, if it's a python list or not by using the type()
function.
print(type(arr))
// output: <class 'list'>
Other Articles You'll Also Like: