
In Python, strings and lists are two fundamental data structures often used together in various applications. Converting a Python string to a list is a common operation that can be useful in many scenarios, such as data preprocessing, text analysis, and more.
This tutorial aims to provide a comprehensive guide on how to convert a string to a list in Python, covering multiple methods, their use cases, and performance considerations. By the end of this tutorial, you will have a solid understanding of how to effectively convert strings to lists in Python, enabling you to tackle a variety of tasks with confidence.
split() is the most common method for converting a delimited string to a list and handles leading and trailing whitespace automatically when called without arguments.list() converts a string into a list of individual characters, including spaces and special characters.json.loads() is the correct method for parsing JSON-encoded strings into Python lists or dictionaries.re.split() handles strings with inconsistent or multiple delimiters using a regular expression pattern.Let’s look at a simple example where we want to convert a string to list of words i.e. split it with the separator as white spaces.
s = 'Welcome To DigitalOcean'
print(f'List of Words ={s.split()}')
Output: List of Words =['Welcome', 'To', 'DigitalOcean']
If you are not familiar with f-prefixed string formatting, please read f-strings in Python
If we want to split a string to list based on whitespaces, then we don’t need to provide any separator to the split() function. Also, any leading and trailing whitespaces are trimmed before the string is split into a list of words. So the output will remain same for string s = ' Welcome To DigitalOcean ' too. Let’s look at another example where we have CSV data into a string and we will convert it to the list of items.
s = 'Apple,Mango,Banana'
print(f'List of Items in CSV ={s.split(",")}')
Output: List of Items in CSV =['Apple', 'Mango', 'Banana']
Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.
s = 'abc$ # 321 '
print(f'List of Characters ={list(s)}')
Output: List of Characters =['a', 'b', 'c', '$', ' ', '#', ' ', '3', '2', '1', ' '] If you don’t want the leading and trailing whitespaces to be part of the list, you can use strip() function before converting to the list.
s = ' abc '
print(f'List of Characters ={list(s.strip())}')
Output: List of Characters =['a', 'b', 'c'] That’s all for converting a string to list in Python programming.
split()The split() method is the most common way to convert a string into a list by breaking it at a specified delimiter.
string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
If you need more control over how elements are added to the list, list comprehension is a powerful option.
string = "hello"
list_of_chars = [char for char in string]
print(list_of_chars) # Output: ['h', 'e', 'l', 'l', 'o']
json.loads() for Structured DataFor parsing JSON-encoded strings, json.loads() is the preferred method.
import json
string = '["apple", "banana", "cherry"]'
list_of_fruits = json.loads(string)
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
| Method | Use Case | Performance |
|---|---|---|
split() |
Simple delimited strings | Fast |
| List Comprehension | Character-by-character conversion | Moderate |
json.loads() |
Parsing structured data | Depends on size |
If delimiters vary, use regular expressions with re.split().
import re
string = "apple,banana;cherry"
list_of_fruits = re.split(r'[;,]', string)
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
Convert JSON-like strings to nested lists.
import json
string = '{"apple": ["red", "green"], "banana": ["yellow", "green"]}'
nested_list = json.loads(string)
print(nested_list) # Output: {'apple': ['red', 'green'], 'banana': ['yellow', 'green']}
Measure the efficiency of different methods with large datasets.
import time
# Method 1: split()
start_time = time.time()
for _ in range(1000000):
string = "apple,banana,cherry"
list_of_fruits = string.split(",")
end_time = time.time()
print(f"Time taken for split(): {end_time - start_time} seconds")
# Method 2: List Comprehension
start_time = time.time()
for _ in range(1000000):
string = "hello"
list_of_chars = [char for char in string]
end_time = time.time()
print(f"Time taken for List Comprehension: {end_time - start_time} seconds")
# Method 3: json.loads()
import json
start_time = time.time()
for _ in range(1000000):
string = '["apple", "banana", "cherry"]'
list_of_fruits = json.loads(string)
end_time = time.time()
print(f"Time taken for json.loads(): {end_time - start_time} seconds")
Yes, you can convert a string to a list using methods like split(), list comprehension, or json.loads(). For example, using split():
string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
You can use .split() for delimited strings or json.loads() for structured data. For example, using json.loads():
import json
string = '["apple", "banana", "cherry"]'
list_of_fruits = json.loads(string)
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
list() in Python?The list() function is a built-in Python function that converts an iterable (like a string, tuple, or set) into a list. This is particularly useful when you need to manipulate individual elements of an iterable or when you want to convert a string into a list of characters. For example, list("hello") would return ['h', 'e', 'l', 'l', 'o'].
split()?You can use list comprehension or list(string) for character-by-character conversion. For example, using list comprehension:
string = "hello"
list_of_chars = [char for char in string]
print(list_of_chars) # Output: ['h', 'e', 'l', 'l', 'o']
split() and list() in Python?split() divides a string by a delimiter, while list() converts each string character into a separate list element. For example:
# Using split()
string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits) # Output: ['apple', 'banana', 'cherry']
# Using list()
string = "hello"
list_of_chars = list(string)
print(list_of_chars) # Output: ['h', 'e', 'l', 'l', 'o']
Use json.loads() to parse structured JSON data into nested lists. Here’s an example:
import json
string = '{"apple": ["red", "green"], "banana": ["yellow", "green"]}'
nested_list = json.loads(string)
print(nested_list) # Output: {'apple': ['red', 'green'], 'banana': ['yellow', 'green']}
In this tutorial, you covered five methods for converting a string to a list in Python: split() for delimited strings, list() for character-by-character conversion, json.loads() for structured data, re.split() for inconsistent delimiters, and list comprehension for fine-grained control. You also saw how method choice affects performance across large datasets.
The right method depends on your input format. For most everyday tasks, split() is the starting point. For JSON data, json.loads() is the only correct choice. For anything more complex, re.split() or list comprehension gives you the control you need.
To go further with Python strings and lists:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
“”" sometimes you do not to import anything to make it work “”" a = ‘test’ b = [] b += a print(b) > Output: [‘t’, ‘e’, ‘s’, ‘t’]
- _zippp
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.