5 Ways to Convert String to a List in Python

Nitika Sharma Last Updated : 24 Oct, 2024
4 min read

Converting a string to a list is a common task in Python programming. It allows us to manipulate and work with individual elements of a string more easily. One popular method for converting a string to a list in Python is using the list() constructor. This constructor takes an iterable, such as a string, and converts it into a list by considering each character as a separate element. In this article, we will explore different methods to convert a string to a list in Python. We will also provide examples and code snippets to demonstrate each method.

Overview:

  • Learn about the importance of string to list conversion in Python.
  • Gain an understanding of different methods like split(), list comprehension, map(), ast.literal_eval(), and regular expressions.
  • Discover how to handle specific cases such as comma-separated values or nested elements.
  • Find tips for efficiently converting strings to lists, including managing empty strings and handling whitespace.

Methods to Convert String to a List in Python

Let us now look at methods to convert string to a list in Python.

Using the split() Method

The first method to convert a string to a list in Python is the split() method. It is a built-in function in Python that splits a Python convert string to list into a list of substrings based on a specified delimiter. By default, the delimiter is a space. Here’s an example:

string = "Hello World"
list = string.split()
print(list)

Output

[‘Hello’, ‘World’]

Using List Comprehension

List comprehension is a concise way to create lists in Python. It allows us to iterate over a string and append each character to a list. Here’s an example:

string = "Hello World"
list = [char for char in string]
print(list)

Output

[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]

Using the map() Function

The map() function applies a given function to each item in an iterable and returns a new list. We can use the map() function and the list() function to convert a string to list python. Here’s an example:

string = "Hello World"
list = list(map(str, string))
print(list)

Output

[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]

Using the ast.literal_eval() Function

The ast.literal_eval() function evaluates a string containing a Python literal or container and returns the corresponding Python object. We can use this function to convert a string to a list. Here’s an example:

import ast
string = "[1, 2, 3, 4, 5]"
list = ast.literal_eval(string)
print(list)

Output

[1, 2, 3, 4, 5]

Using Regular Expressions

Regular expressions provide a powerful way to manipulate strings in Python. We can use the re.split() function from the re module to split a string into a list based on a regular expression pattern. Here’s an example:

import re
string = "Hello,World"
list = re.split(r',', string)
print(list)

Output

[‘Hello’, ‘World’]’

Also read: 5 Ways of Finding the Average of a List in Python

Examples of Python String to List Conversion

Converting a Comma-Separated String to a List

string = "apple,banana,orange"
list = string.split(',')
print(list)

Output

[‘apple’, ‘banana’, ‘orange’]

Converting a String with Nested Elements to a List

import ast
string = "[1, [2, 3], [4, [5, 6]]]"
list = ast.literal_eval(string)
print(list)

Output

[1, [2, 3], [4, [5, 6]]]

Also Read: 90+ Python Interview Questions

Tips for Efficient Python String to List Conversion in Python

Let us look at tips to efficiently convert strings to a list in Python.

Handling Empty Strings

Converting an empty string to a list Python will result in an empty list. It is important to handle this case to avoid any unexpected errors in your code.

Dealing with Whitespace and Punctuation

When using the split() method or regular expressions to split a string into a list, be aware of leading or trailing whitespace and punctuation marks. These can affect the resulting list.

Handling Error Cases

When using the ast.literal_eval() function, ensure the string to list python contains a valid Python literal or container. Otherwise, it may raise a ValueError.

Conclusion

Converting a string to a list is a fundamental operation in Python programming. In this article, we explored various methods to achieve this conversion, including using the split() method, list comprehension, the map() function, ast.literal_eval(), and regular expressions. We also provided examples and code snippets to demonstrate each method. By understanding these techniques, you can efficiently convert strings to lists and manipulate them as needed in your Python programs.

If you are looking for a Python course online, Explore – Learn Python for Data Science.

Frequently Asked Questions

Q1. Can we convert a string to a list in Python?

A. Yes, you can convert a string to a list in Python using the list() function or the split() method. The list() function will break the string into individual characters, while split() breaks the string into a list of words based on a specified delimiter (default is whitespace).
string = “hello”
list_of_chars = list(string) # [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
words = “hello world”.split() # [‘hello’, ‘world’]

Q2. How to turn a list into a string in Python?

A. You can turn a list into a string using the join() method. This method concatenates the elements of the list into a single string, with an optional separator.
list_of_words = [‘hello’, ‘world’]
string = ‘ ‘.join(list_of_words) # ‘hello world’

Q3. How do you convert a string to a list of lists in Python?

A. To convert a string to a list of lists, first split the string into individual strings (e.g., lines or words), then split those further as needed.
string = “1,2,3;4,5,6”
list_of_lists = [s.split(‘,’) for s in string.split(‘;’)] # [[‘1’, ‘2’, ‘3’], [‘4’, ‘5’, ‘6’]]

Q4. How to split a string into a list in Python?

A. To split a string into a list, use the split() method, specifying the delimiter if necessary. The default delimiter is any whitespace.
string = “hello world”
list_of_words = string.split() # [‘hello’, ‘world’]
custom_split = “one,two,three”.split(‘,’) # [‘one’, ‘two’, ‘three’]

Hello, I am Nitika, a tech-savvy Content Creator and Marketer. Creativity and learning new things come naturally to me. I have expertise in creating result-driven content strategies. I am well versed in SEO Management, Keyword Operations, Web Content Writing, Communication, Content Strategy, Editing, and Writing.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details