You are currently viewing Convert String to List in Python

How to convert a string to a list in Python? To convert a string to a list in Python, you can use the split() method. The split() method splits a string into a list of substrings based on a specified delimiter. If no delimiter is provided, it splits the string at whitespace characters by default.

Advertisements

You can convert a string to a list in Python using many ways, for example, by using split(), list comprehension, string slicing, enumerate, re.findall(), list(), map(), lambda, json.loads(), ast.literal functions. In this article, I will explain how to convert a string to a list by using all these functions with examples.

1. Quick Examples of Converting String to List

If you are in a hurry, below are some quick examples of how to convert a string to a list.


# Quick examples of converting string to list

# Example 1: Convert string to list 
# Using split() function
string = "Welcome to Sparkbyexample.com"
result = string.split()

# Example 2: Split string and convert to list
# using split() with specified delimeter
string = "Python,Spark,Hadoop"
result = string.split(",")

# Example 3: Convert string to list 
# Using list comprehension 
string = "Python"
result = [i for i in string]

# Example 4: Using string slicing
string = "spark"
def Convert(string):
    mylist = []
    mylist[:0] = string
    return mylist  
result = Convert(string)

# Example 5: Using enumerate function
string = "spark"
mylist = [i for _, i in enumerate(string) ]

# Example 6: Using re.findall() method 
string = "spark"
def Convert(string):
    return re.findall('[a-zA-Z]', string)
result = Convert(string)

# Example 7: Using list() function
string = "spark"
result = list(string)

# Example 8: Using map() function
string = "spark"
result = list(map(str, string))

# Example 9: Using lambda function
string = "spark"
result = list(filter(lambda i:(i in string),string))

# Example 10: Using JSON loads() function
result = json.loads(string)

# Example 11: Using ast.literal function
string = '["Python", 2500, "Pandas", 2000, "Hadoop", 2500]'
result = ast.literal_eval(string)

2. Convert String to List Using split() Function

You can convert a string to a list using split() function. For example, first initializes a string and then apply converts it to a list using the split() function. The split() function splits the string at whitespace characters by default, resulting in a list where each word becomes an element in the list.


# Initialize string
string = "Python Spark Haddop"
print("Original String:", string)

# Convert string to list 
# Using split() function
result = string.split()
print("List from strings:", result)

Yields below output.

python convert list string

If you want to split the string based on a different delimiter, you can pass it as an argument to the split() function. In this program, the split() function splits the string at each comma (",") character, resulting in a list, [‘Python’, ‘Spark’, ‘Hadoop’].


# Initialize string
string = "Python,Spark,Hadoop"
print("Original String:", string)

# Split string and convert to list
# using split() with specified delimeter
result = string.split(",")
print("List from strings:", result)

Yields below output.

python convert list string

3. Convert String to List Using List Comprehension

You can also convert a string to a list using list comprehension in Python, you can iterate over each character in the string and create a new list with each character as an element of the list.

In the below example, the list comprehension [i for i in string] creates a new list result. The expression represents each character in the string variable, and it is appended to the list result variable. As a result, each character becomes an element in the resulting list.


# Initialize string
string = "Python"
print("Original String:", string)

# Convert string to list 
# Using list comprehension 
result = [i for i in string]
print("List from strings:", result)

# Output:
# Original String: Python
# List from strings: ['P', 'y', 't', 'h', 'o', 'n']

4. Convert String to List Using String Slicing

You can also convert the string to a list using string slicing. It initializes a string and defines a function Convert() to perform the conversion. In the Convert() function, an empty list mylist is created. Then, the slice mylist[:0] is used to insert each character from the string string at the beginning of the list. This effectively splits the string into individual characters and creates a list with each character as an element.


# Initialize string
string = "spark"
print("Original String:", string)

# Using string slicing
def Convert(string):
    mylist = []
    mylist[:0] = string
    return mylist  
result = Convert(string)
print("List from strings:", result)

# Output:
# Original String: spark
# List from strings: ['s', 'p', 'a', 'r', 'k']

5. Convert String to List Using Enumerate Function 

You can also convert a string to a list using the enumerate() function in Python, you can iterate over the string and use the enumerate() function to get both the index and value of each character.

In the below example, the list comprehension [i for _, i in enumerate(string)] creates a new list mylist. The enumerate() function returns a tuple with the index and value of each character in the string. Using the "-" placeholder for the index (which you are not using), you only retrieve the value (character) and append it to the list mylist.


# Initialize string
string = "spark"
print("Original String:", string)

# Using enumerate function
mylist = [i for _, i in enumerate(string) ]
print("List from strings:", mylist)

Yields the same output as above.

6. Convert String to List Using re.findall() Method

You can also use the re.findall() method from the re module to convert a string to a list of alphabetic characters. It initializes a string and defines a Convert() function to perform the conversion.

In the Convert() function, the re.findall() method is used to find all occurrences of alphabetic characters [a-zA-Z] in the string string. It returns a list containing all the matching characters, effectively converting the string to a list of alphabetic characters.


import re

# Initialize string
string = "spark"
print("Original String:", string)

# Using re.findall() method 
def Convert(string):
    return re.findall('[a-zA-Z]', string)
  
result = Convert(string)
print("List from strings:", result)

Yields the same output as above.

7. Convert String to List Using list() Function

You can also convert a string to a list using the list() function in Python, you can pass the string as an argument to the list() function. The list() function will split the string into individual characters and create a list with each character as an element.

In the below example, the list() function is used to convert the string string into a list result. The list() function splits the string into individual characters and creates a list where each character becomes an element.


# Initialize string
string = "spark"
print("Original String:", string)

# Using list() function
result = list(string)
print("List from strings:", result)

Yields the same output as above.

8. Convert String to List Using map() Function

Similarly, you can also convert a string to a list using the map() function in Python, you can apply the list() function to the result of mapping each character of the string to a list. For example, the map() function applies the str() function to each character of the string string. The resulting map object is then converted to a list using the list() function, resulting in a list where each character from the original string is an element.


# Initialize string
string = "spark"
print("Original String:", string)

# Using map() function
result = list(map(str, string))
print("List from strings:", result)

Yields the same output as above.

9. Convert String to List Using Lambda Function

You can also use a lambda function along with the filter() function to convert a string to a list. It initializes a string, applies the lambda function to each character using the filter() function, and then converts the filtered result to a list.

In the below example, the lambda function lambda i:(i in string) checks if each character i is present in the string string. The filter() function applies this lambda function to each character of the string and only the characters that evaluate to True are kept. Finally, the filtered result is converted to a list using the list() function.


# Initialize string
string = "spark"
print("Original String:", string)

# Using lambda function
result = list(filter(lambda i:(i in string),string))
print("List from strings:", result)

Yields the same output as above.

10. Using JSON loads() Function

You can also convert a string to a list using JSON in Python, you can utilize the loads() function of json module. The loads() function parses a JSON-formatted string and returns a corresponding Python object. In this case, you can parse the string as a JSON array and convert it to a list. For example, you import the json module. The string variable represents a JSON-formatted array of strings. The json.loads() function parses the string and returns a Python object.


import json

# Initialize string
string = '["Python", "Spark", "Hadoop"]'
print("Original String:", string)

# Using JSON loads() function
result = json.loads(string)
print("List from string:", result)


# Output:
# Original String: ["Python", "Spark", "Hadoop"]
# List from string: ['Python', 'Spark', 'Hadoop']

11. Convert String to List Using ast.literal Function

You can also convert a string to a list using the ast.literal_eval() function from the ast module in Python, you can evaluate the string as a literal expression. The ast.literal_eval() function safely evaluates a string containing a Python literal and returns the corresponding Python object.


import ast

# Initialize string
string = '["Python", 2500, "Pandas", 2000, "Hadoop", 2500]'
print("Original String:", string)

# Using ast.literal function
result = ast.literal_eval(string)
print("List from string:", result)

Yields the same output as above.

Conclusion

In this article, I have explained how to convert a string to a list in Python by using split(), list comprehension, string slicing, enumerate, re.findall(), list(), map(), lambda, json.loads() and ast.literal functions with examples.

Happy Learning !!