Loading...

How to convert a string to a list in python?

How to convert a string to a list in python?

In this blog, we are going to talk about multiple ways to convert a string to a list in python with examples. Do not worry, if you are not aware of strings and lists. We will also discuss them.

Introduction

Lists and strings are often used in python. There are a variety of data types in python. Some of them are strings, lists, tuples, integers, dictionaries, floats, booleans, etc. Let us explore what are lists and are strings in python.

What are strings in python?

A set of characters is known as strings. In python, they are enclosed in double quotes( “”) or single quotes( ” ). We cannot change the value of a string. Even a small change in the existing string will be considered a new string. They are case-sensitive. Each of the characters in a string is indexed. The first character of the string is indexed as zero and it gets incremented for each character towards the right till the last character of the string. They are frequently used in python. There are many functions and methods available for strings to make working with them easier. Below given is an example of what it looks like.

x = "codedamn"
Code language: Python (python)

What are lists in python?

A set of elements enclosed in square brackets( [] ) are known as a list. The elements can be of any data type. They are separated by commas( , ). Each of the elements in a list is indexed. The first element of the list is indexed as zero and it gets incremented for each element towards the right till the last element of the list. With the help of indices, we can access any element of the list very easily. Lists are very flexible to use. We can change the elements of a list very easily.  There are many methods available for lists to make working with them easier. Below given is an example of what a typical list in python looks like.

y = ["W", "e", "b", 3]
Code language: Python (python)

Ways to convert a string to a list in python

Working with lists is much easier than working with strings. Lists give much more flexibility than strings. We can include data of any type in lists whereas, in strings, we can include only characters. Even when data of another type is included, it gets converted to a string. Moreover, you will come across many situations, where you need to convert a string to a list.

Using split() method

There are two optional parameters for this method. The split() method divides the string into the elements of a list as per the parameters we specify.

Syntax:

string.split(parameter1, parameter2)
Code language: Python (python)

Parameter1:

When converting a string to a list, we have to specify at what intervals we should split the string, so that we can put the set of characters between each split as an element of the list. We have to put that in this parameter. When we do not specify this parameter, it takes space as the position when the string gets split.

Parameter2:

In this parameter, we can specify how many times we need to split the string. It is an optional parameter. When we do not specify this parameter, it splits all the occurrences of the parameter1.

Example 01

string1 = "football" list1 = string1.split() print(list1)
Code language: Python (python)

The output of the above code is shown below.

['football']
Code language: Bash (bash)

As we didn’t specify the value of parameter1, the entire string became the only element of the list. Also, as we didn’t specify parameter2, all the occurrences got split.

Example 02

string1 = "foot,ball" list1 = string1.split(",") print(list1)
Code language: Python (python)

The output of the above code is shown below.

['foot', 'ball']
Code language: Bash (bash)

In this example, we have specified parameter1 as a comma( , ). In the string we have taken as an example, we have a comma at index 4. So the string got split at that point.

string1 = "foot,b,a,l,l" list1 = string1.split(",", 1) print(list1)
Code language: Python (python)

The output of the above code is shown below.

['foot', 'b,a,l,l']
Code language: Bash (bash)

In this example, as we have specified the parameter1 as a comma( , ) the string has to get split all the occurrences of a comma but as we also have specified the parameter2 as 1, it splits only once. So we have got the output as above.

Using list() method

This method has only one parameter. We have to pass the variable’s name as a parameter to the list() method. Not just strings, we can use this method for converting sets, tuples, dictionaries, etc into lists. In the case of a dictionary, all the keys of the dictionary get converted to the elements of a list, when we use the list() method. Let us understand this method.

string2 = "football" list2 = list(string2) print(list2)
Code language: Python (python)

The output of the above code is shown below.

['f', 'o', 'o', 't', 'b', 'a', 'l', 'l']
Code language: Bash (bash)

Using map()

It has two parameters. The first one is a function. The second one is an iterable datatype. The function gets applied on each element of the iterable datatype and the output is given accordingly. We can use this method to convert a string to a list.

string3 = "football" list3=list(map(str,string3)) print(list3)
Code language: Python (python)

The output of the above code is shown below.

['f', 'o', 'o', 't', 'b', 'a', 'l', 'l']
Code language: Bash (bash)

We can see in the above example that all the characters of the string got converted to elements of a list.

Using loop

Firstly, we should define an empty loop. Then we should add each character of the string to the list using the append function. We can access each character of the string using a for loop. 

string4 = "football" list4 = [] for i in string4:     list4.append(i) print(list4)
Code language: Bash (bash)

The output of the above code is shown below.

['f', 'o', 'o', 't', 'b', 'a', 'l', 'l']
Code language: Bash (bash)

Using list comprehension

This method is preferred over traditional loops methods as it is more efficient than loops. Let us see how we can convert a string using list comprehension.

string5 = "ball" list5 = [i for i in string4] print(list5)
Code language: Python (python)

The output of the above code is shown below.

['b', 'a', 'l', 'l']
Code language: Bash (bash)

Using enumerate function

We can use enumerate function to convert a string to a list. It has only one parameter. We have to pass the variable in which the string is stored as a parameter. Let us see how we can use the enumerate function.

string6 = "code" list6=[i for a,i in enumerate(string6)] print(list6)
Code language: Python (python)

The output of the above code is shown below.

['c', 'o', 'd', 'e']
Code language: Bash (bash)

Using JSON

We use json.loads() function to parse a string and convert it into a list. Finally, we can print the list.

import json string7 = '["code", 1,"damn", 2]' list7 = json.loads(string7) print(list7)
Code language: Python (python)

The output of the above code is shown below.

['code', 1, 'damn', 2]
Code language: Bash (bash)

Using re.findall() method

We can convert a string to a list using the re.findall() method of the re library. It has three parameters out of which the first two are compulsory whereas the last one is optional. The first parameter is the pattern that you want to find in the string. The second one is the string that you want to convert. The third parameter is the condition which can be given if needed. Let us understand how we can use this method with the help of an example.

import re string8 = "web" list8 = re.findall("[a-z]",string8) print(list8)
Code language: Python (python)

The output of the above code is shown below.

['w', 'e', 'b']
Code language: Bash (bash)

We can see that each of the characters of the string got converted to elements of the list.

Using ast.literal

We can convert a string to a list using the ast.literal_eval() method of the ast library. We have to pass the string as a parameter to this method. Let us understand how we can use this method with the help of an example.

import ast string9 = '["code", 1,"damn", 2]' list9 = ast.literal_eval(string9) print(list9)
Code language: Python (python)

The output of the above code is shown below.

['code', 1, 'damn', 2]
Code language: Bash (bash)

Using string slicing

String slicing is a technique in python to extract a set of characters from the existing string. It has three parameters. The first parameter is the start position of the string from which you want to slice, the second parameter is the end position and the third parameter is the number of steps you want to jump at a time. The output of a string slice is also a string. You would have been wondering if the output that we get is also a string, how can we convert it to a list? Let us understand how we can use this method with the help of an example.

string = "web" list = [] list[:0] = string print(list)
Code language: Python (python)

The output of the above code is shown below.

['w', 'e', 'b']
Code language: Bash (bash)

Conclusion

As we have already discussed, working with lists is much easier than working with strings. So we need to know how to convert them to each other. This is the end of this article. Do check out this python course at codedamn to start learning python from scratch with hands-on experience. At codedamn, we have clear learning paths to accelerate your learning. With clear roadmaps, you will have a clear idea about your learning progress. There are playgrounds at codedamn, in which you can code directly. Make sure you join codedamn’s community. If you had any doubts while you are reading this article, do post them in the comment section of this article.

Frequently Asked Questions- FAQ

What are lists in python?

A set of elements enclosed in square brackets( [] ) are known as a list.

What are strings in python?

A set of characters is known as strings.

Why do we need to convert a string to a list?

Working with lists is much easier than working with strings. Lists give much more flexibility than strings.

Why split() method is used?

The split() method divides the string into the elements of a list as per the parameters we specify.

What are the parameters of the list() method?

We have to pass the variable in which the string is stored as a parameter.

What is string slicing in python and what are its parameters?

String slicing is a technique in python to extract a set of characters from the existing string. It has three parameters. The first parameter is the start position of the string from which you want to slice, the second parameter is the end position and the third parameter is the number of steps you want to jump at a time.

What are the parameters of the map() method?

The first parameter is a function. The second parameter is an iterable datatype. The function gets applied on each element of the iterable datatype.

Sharing is caring

Did you like what Manish wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far