Open In App

Python | Program to convert String to a List

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the user’s choice, are encountered. To do this we use the split() method in string.

Examples:

Input : "Geeks for Geeks"
Output : ['Geeks', 'for', 'Geeks']
Explaination:Here we have a string in the input which we converted into list of words.

String to List Conversion in Python

Below are the methods that we will cover in this article:

  • Using list()
  • Using list comprehension 
  • Using split() method
  • Using string slicing
  • Using re.findall() method
  • Using enumerate function 
  • Using JSON
  • Using ast.literal

Python String to List of Characters using list() method

The list is the built-in datatype in Python. it is generally used to store the item or the collection of items in it and we can use it to convert the string to a list.

Python
s = "Geeks for"
x = list(s)
print(x)

Output:

['G', 'e', 'e', 'k', 's', ' ', 'f', 'o', 'r']

Python String to List of Characters using List Comprehension 

Here we can also use list comprehension in which we iterate over the string and store it in the list

Python
s="Geeks"
x=[i for i in s]
print(x)

Output
['G', 'e', 'e', 'k', 's']


Python Convert String to List using split() method

The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Example 1

Python
# Python code to convert string to list


def Convert(string):
    li = list(string.split(" "))
    return li


# Driver code
str1 = "Geeks for Geeks"
print(Convert(str1))

Output
['Geeks', 'for', 'Geeks']




Example 2

Python
def Convert(string):
    li = list(string.split("-"))
    return li


# Driver code
str1 = "Geeks-for-Geeks"
print(Convert(str1))

Output

['Geeks', 'for', 'Geeks']

Python Convert String to List using String Slicing

In Python, we have Slicing with which we can slice any iterable data according to our needs and use it as required

Python
def Convert(string):
    list1 = []
    list1[:0] = string
    return list1


# Driver code
str1 = "ABCD"
print(Convert(str1))

Output
['A', 'B', 'C', 'D']



Python Convert String to List using re.findall() method 

This task can be performed using regular expression. We can use the pattern to match all the alphabet and make a list with all the matched elements. 

Python
import re

# Function which uses re.findall method to convert string to list character wise
def Convert(string):
    return re.findall('[a-zA-Z]', string)
    
# Driver code
str1="ABCD"
print("List of character is : ",Convert(str1))

Output
List of character is :  ['A', 'B', 'C', 'D']


Python Convert String to List using enumerate function 

Python has an inbuilt method enumerate which can use to convert a string to a list

Python
s="geeks"
x=[i for a,i in enumerate(s) ]
print(x)

Output
['g', 'e', 'e', 'k', 's']


Python Convert String to List using JSON

The json module in Python provides functions for working with JSON data. It also has loads method which can

Python
import json

stringA = '["geeks", 2,"for", 4, "geeks",3]'

# Type check

res = json.loads(stringA)
# Result
print("The converted list : \n",res)

Output
The converted list : 
 ['geeks', 2, 'for', 4, 'geeks', 3]


Python Convert String to List using ast.literal

In Python, we have ast module which has a method of litera_eval through which we can also do the conversion

Python
import ast

# initializing string representation of a list
ini_list = '["geeks", 2,"for", 4, "geeks",3]'


# Converting string to list
res = ast.literal_eval(ini_list)

# printing final result and its type
print(res)
print(type(res))

Output
['geeks', 2, 'for', 4, 'geeks', 3]
<class 'list'>


Python | Program to convert String to a List – FAQs

How to convert a sentence into a list of words in Python?

You can use the split() method to split a sentence into a list of words based on whitespace:

sentence = "Hello world how are you"
word_list = sentence.split()
print(word_list)

Output:

['Hello', 'world', 'how', 'are', 'you']

How to convert list of strings to list of words in Python?

If you have a list of strings and want to combine them into a single list of words:

string_list = ["Hello", "world", "how", "are", "you"]
word_list = [word for string in string_list for word in string.split()]
print(word_list)

Output:

['Hello', 'world', 'how', 'are', 'you']

How to convert string to list using map in Python?

You can use the map() function along with split() to convert a string into a list of words:

string = "Hello world how are you"
word_list = list(map(str, string.split()))
print(word_list)

Output:

['Hello', 'world', 'how', 'are', 'you']

How to convert string into list in Python without split?

If you want to convert a string into a list of characters without using split():

string = "Hello"
char_list = list(string)
print(char_list)

Output:

['H', 'e', 'l', 'l', 'o']

How do I convert a string to a list without spaces in Python?

To convert a string into a list of words or phrases without spaces, you can use regular expressions (re.split()) to split based on non-alphanumeric characters:

import re
string = "Hello,world!how-are?you"
word_list = re.split(r'\W+', string)
print(word_list)

Output:

['Hello', 'world', 'how', 'are', 'you']

This splits the string string into a list of words based on non-alphanumeric characters (\W+), effectively removing spaces and punctuation from consideration.



Similar Reads

Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python Program to convert List of Integer to List of String
Given a List of Integers. The task is to convert them to a List of Strings. Examples: Input: [1, 12, 15, 21, 131]Output: ['1', '12', '15', '21', '131']Input: [0, 1, 11, 15, 58]Output: ['0', '1', '11', '15', '58']Method 1: Using map() [GFGTABS] Python3 # Python code to convert list of # string into sorted list of integer # List initialization list_i
5 min read
Python | Convert list of tuples to list of list
This is a quite simple problem but can have a good amount of application due to certain constraints of Python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let's discuss certain ways in which we can convert a list of tuples to list of list. Method #1: Using list compr
8 min read
Python | Convert a string representation of list into list
Many times, we come across the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to a list in Python to perform tasks is quite common in web development. Convert a string of a list in
6 min read
Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python | Convert list of numerical string to list of Integers
Many times, the data we handle might not be in the desired form for any application and has to go through the stage of preprocessing. One such kind of form can be a number in the form of a string that too is a list in the list and we need to segregate it into digit-separated integers. Let's discuss certain ways in Python in which this problem can b
6 min read
Python | Convert string enclosed list to list
Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1: Python eval() The eval() method parses the expression passed to this method and runs python expression (code)
5 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read