×

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

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.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 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 open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.