×

How to Convert String to List In Python?

How to Convert String to List In Python?

We all are familiar with what strings and lists are, let us have a quick revision on them-

Strings are a sequence of characters that are denoted using inverted commas ''. They are immutable which means they cannot be changed once declared. The distinction between the two strings can be understood using id().

Examples of a string are-

 a=’Bill Gates’
 x=’Moscow’ 

The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [ ]. Lists are mutable which means their values can be changed. An example of a list is-

list1 = [23,’Apple’,3.5,’Mangoes’]

In this article, we will discuss various ways of converting a string to a list in Python.

The following list contains the methods we will be elucidating in detail-

  1. Using the split function.
  2. Using list ().
  3. Converting float numbers into a list of lists.
  4. Using json module
  5. Using ast module

Using split function

The split function in Python is used to convert a string into a list. The parameters of this function are separator and maxsplit.

The separator tells us about the delimiter or the part at which the string should be split. By default, white space is considered a separator.

The maxsplit parameter tells us about the maximum number in which our string should be splitted.

Following program illustrates the working of split function-

 sname="Tutorials and Examples" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 print("The string after converting to list {}".format(sname.split())) #using split function 

Input-

Convert String to List

Output-

Convert String to List

Once the program is executed we can see that the given string is converted into a list whose data type can be checked using the type function.

2. Using list()

The list() takes the specified string as a sequence and converts it into a list.

Following program illustrates the working of list()-

 sname="Tutorials and Examples" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 print("The string after converting to list of characters {}".format(list(sname))) 

Input-

Convert String to List

Output-

Convert String to List

In the output we can observe after using list(), the string is converted to a list and each element in the list is the character of our string.

In the next example, we will pass float integers as a string and then apply list().

Let us have a look at the program-

 sname="1.2 2.3 3.4 4.5 5.6" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 print("The string after converting to list of float numbers {}".format(list(sname))) 

Input-

Convert String to List

Output-

Convert String to List

In the output, we can see a list is returned whose each element is a number and a special character (.).

3. Converting float numbers into a list of lists.

In this example we will discuss how we can return a list of lists, we will use the split function and map() here.

We have seen how the split function works in the previous example, here will see how the map() adds its functionality to every element of our list and makes our program more meaningful.

It takes function and sequence as parameters.

The function that we have provided here is ‘list’ and the sequence is ‘slist’ which is the list obtained from the split function.

Following program illustrates how we can convert the string of float numbers into a list of lists.

 sname="1.2 2.3 3.4 4.5 5.6" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 slist=sname.split()
 print(slist)
 listc=list(map(list,slist))
 print(listc) 

Input-

Convert String to List

Output-

Convert String to List

In the output, we can observe a list that has lists of numbers.

4. Using json module

There is a module in Python called 'json' which can be used to work with the json data (JSON stands for JavaScript Object Notation). It takes a valid string and converts it into a dictionary. Here we will be using json.loads() to convert our string to a list.

The important thing that we must take care of is that our input should be numeric.

Following program illustrates how we can convert the string to lists by importing the json module.

 import json
 sname="[1,2,3,4,5]" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 slist=json.loads(sname)
 print(slist)
 print(type(slist)) 

Input-

Convert String to List

Output-

Convert String to List

In the output, we can observe it returns the type of sname as a string and then after applying json.loads() it converts our input string to a list which can be verified using the type function.

4. Using ast module

AST stands for abstract syntax trees. This module is used to check what the current grammar looks like concerning our program.

Here ast.literal_eval() takes a string as an input and converts it to a list.

Following program illustrates how we can convert the string to lists by importing the ast module.

 import ast
 sname="[1,2,3,4,5]" #declaring the string
 print(sname) #printing the string
 print(type(sname)) #printing the type of string
 slist=ast.literal_eval(sname)
 print(slist)
 print(type(slist)) 

Input-

Convert String to List

Output-

Convert String to List

In the output, we can observe it returns the type of sname as a string, and then after applying ast.literal_eval() it converts our input string to a list which can be verified using the type function.

So, in this article, we discussed the various ways of converting a string to a list in Python.


Related Topics

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.