How to Convert String to List in Python?

Recently, one of my colleagues who works on machine learning asked me about converting a string to a list in Python. I explained to them various methods through which we can achieve this task. In this tutorial, I will explain some important methods to convert string to list in Python along with examples.

Convert String to List in Python

Before getting into the methods, let’s establish what we’re trying to accomplish. When we talk about converting a string to a list in Python, we typically mean one of two things:

  1. Breaking a string into individual characters
  2. Splitting a string into substrings based on a delimiter

Each approach has its use cases, and Python provides several elegant ways to handle both.

Read How to Replace Values in a List Using Python?

Method 1: Use the split() Method

Python split() method is one of the simplest ways to convert a string to a list. It divides the string at the specified separator and returns a list of substrings.

Syntax:

str.split(sep=None, maxsplit=-1)
  • sep: The delimiter string. If not specified, any whitespace string is a separator.
  • maxsplit: The maximum number of splits. If not specified, there is no limit.

Example:

Here is an example.

address = "123 Main Street, Springfield, IL"
address_list = address.split(", ")
print(address_list)

Output:

['123 Main Street', 'Springfield', 'IL']

You can see the exact output in the screenshot below:

string to list python

The split() method is efficient and can handle various delimiters. Without arguments, it splits on whitespace by default, which is perfect for processing space-separated words.

When to Use split():

  • When your string has a clear delimiter (spaces, commas, etc.)
  • When you need to parse structured text data
  • When working with CSV-like strings

Check out How to Shuffle a List in Python?

Method 2: Use the list() Function

If you need to break a string into individual characters, the list() function in Python provides a simple solution:

Syntax:

list(string)

Example:

Let me show you an example.

city = "Chicago"
city_list = list(city)
print(city_list)

Output:

['C', 'h', 'i', 'c', 'a', 'g', 'o']

You can see the exact output in the screenshot below:

python string to list

This method converts each character in the string to an element in the resulting list.

When to Use list():

  • When you need to process each character individually
  • For creating character frequency maps
  • When implementing string manipulation algorithms

Read How to Convert a Dictionary to a List in Python?

Method 3: Use List Comprehension

Python list comprehension provides a concise way to create lists. You can use it to convert a string to a list of characters or to apply a condition.

Example:

state = "California"
state_list = [char for char in state]
print(state_list)

Output:

['C', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a']

You can see the exact output in the screenshot below:

convert string to list python

List comprehension is not only efficient but also provides better performance for larger strings compared to traditional loops.

When to Use List Comprehension:

  • When you need to apply transformations during conversion
  • For more complex string parsing logic
  • When performance is important for larger datasets

Check out How to Randomly Select from a List in Python?

Method 4: Use Regular Expressions with re.findall()

For more complex string splitting in Python, you can use the re module’s findall() function. This is particularly useful for extracting patterns.

Example:

Here is an example.

import re

phone_number = "Call me at 123-456-7890 or 987-654-3210"
numbers = re.findall(r'\d{3}-\d{3}-\d{4}', phone_number)
print(numbers)  # output: ['123-456-7890', '987-654-3210']

The re.findall() function returns all non-overlapping matches of a pattern in a string as a list, making it ideal for extracting specific data types from text.

When to Use re.findall():

  • When extracting data with specific patterns
  • For complex text parsing requirements
  • When working with unstructured text data

Read How to Remove Duplicates from a List in Python?

Method 5: Use String Literals with ast.literal_eval()

Sometimes you might encounter string representations of Python lists (especially when dealing with APIs or saved data). The ast.literal_eval() function safely converts these string literals back to actual lists:

Example:

Let me show you an example.

import ast

string_list = "['apple', 'orange', 'banana']"
actual_list = ast.literal_eval(string_list)
print(actual_list)  # Output: ['apple', 'orange', 'banana']
print(type(actual_list))  # Output: <class 'list'>

This method is safer than using eval() as it only evaluates strings containing Python literals.

When to Use ast.literal_eval():

  • When processing string representations of Python data structures
  • When parsing JSON-like strings
  • When working with serialized Python objects

Check out How to Find Duplicates in a Python List?

Method 6: Use the splitlines() Method for Multiline Strings

When working with multiline text, the splitlines() method is perfect for converting the string into a list of lines:

multiline_text = """First line
Second line
Third line"""

lines = multiline_text.splitlines()
print(lines)  # Output: ['First line', 'Second line', 'Third line']

This is especially useful when processing configuration files, logs, or any text data with line breaks.

When to Use splitlines():

  • When processing multiline text
  • When parsing log files or configuration files
  • When you need to handle different types of line separators

Compare the Performance of all Methods Used to Convert String to List

I’ve benchmarked these methods to help you make informed decisions based on performance considerations:

MethodSmall StringsLarge StringsFlexibilityComplexity
split()FastFastMediumLow
list()Very FastMediumLowLow
List ComprehensionFastFastHighMedium
re.findall()MediumSlowVery HighHigh
ast.literal_eval()SlowVery SlowLowMedium
splitlines()FastFastMediumLow

Read How to Create an Empty List in Python?

Real-Time Applications

Let me show you some real-time applications for converting strings to lists.

Data Cleaning and Analysis

When working on data analysis projects, I often need to clean and transform text data:

# Processing a CSV-like string from a database
raw_data = "Mike,32,California,90210,Software Developer"

# Convert to list and extract relevant information
data_list = raw_data.split(',')
name, age, state, zip_code, occupation = data_list

# Now I can use these variables separately
print(f"{name} is a {occupation} from {state}")  # Output: Mike is a Software Developer from California

Natural Language Processing

When building NLP applications, converting text to word tokens is a fundamental step:

text = "Natural language processing is fascinating and powerful."

# Tokenization
words = text.lower().split()
print(words)  # ['natural', 'language', 'processing', 'is', 'fascinating', 'and', 'powerful.']

# Further cleaning (removing punctuation)
import re
clean_words = [re.sub(r'[^\w\s]', '', word) for word in words]
print(clean_words)  # ['natural', 'language', 'processing', 'is', 'fascinating', 'and', 'powerful']

Web Scraping and API Integration

When extracting data from websites or APIs, I often need to parse string responses:

# Simulated JSON response from an API
api_response = '{"tags": "python,programming,data science,machine learning"}'

# Extract tags as a list
import json
data = json.loads(api_response)
tags = data['tags'].split(',')
print(tags)  # Output: ['python', 'programming', 'data science', 'machine learning']

Check out How to Remove All Instances of an Element from a List in Python?

Common Challenges and Solutions

Let me explain to you a few common challenges that are faced during the conversion of string to list and also solutions.

Challenge 1: Preserve Delimiters

When using .split(), the delimiter is removed. If you need to keep the delimiter as part of the output, using re.split() with capturing groups is a better approach.

import re
text = "apple,orange,banana"
result = [substring for substring in re.split(r'(,)', text) if substring]
print(result)  # Output: ['apple', ',', 'orange', ',', 'banana']

When parsing structured text where the delimiter matters (e.g., processing logs, structured data).

Challenge 2: Handle Quoted Strings

Splitting a string with comma-separated values (CSV format) can break quoted values incorrectly. Python’s csv.reader correctly handles such cases.

import csv
from io import StringIO

text = 'John,"Smith, MD",Chicago'
reader = csv.reader(StringIO(text))
parsed_data = list(reader)[0]
print(parsed_data)  # Output: ['John', 'Smith, MD', 'Chicago']

When handling CSV files where names, addresses, or job titles contain commas inside quotes.

Challenge 3: Convert Nested Structures

If a string represents a nested JSON structure, a simple .split() won’t work. Instead, Python json.loads() can parse it into a dictionary.

import json

nested_json = '{"name": "Alex", "hobbies": ["hiking", "photography", "coding"]}'
data = json.loads(nested_json)
hobbies_list = data["hobbies"]
print(hobbies_list)  # Output: ['hiking', 'photography', 'coding']

When working with API responses or configuration files stored in JSON format

Read How to Remove an Element from a List by Index in Python?

Conclusion

In this tutorial, I explained how to convert string to list in Python. I discussed important methods to accomplish this task such as using the split() method, list() method, list comprehension, re.findall() method, ast.literal_eval(), and splitlines() method for multiline string. I also explained the comparison of the performance of different methods, real-time applications, and some challenges and solutions.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.