How to convert a string to a list in Python

In Python, both strings and lists are fundamental data types, each serving distinct purposes and exhibiting unique characteristics. A string is a sequence of characters enclosed within single quotes (' ') or double quotes (" "). On the other hand, a list is an ordered collection of elements enclosed within square brackets [ ].

String to List
String to List

Implementation

Several methods are available to convert a string to a list in Python. Here are some of the most common ones:

  • Using list()

  • Using enumerate function 

  • Using list comprehension 

  • Using split() method

  • Using string slicing

  • Using re.findall() method

Using the split() method

This method splits the string based on a specified delimiter and returns the split string as a list. For example:

string = "Welcome to Educative"
list = string.split()
print(list) # Output: ['Welcome', 'to', 'Educative']

Complexity

  • Time: O(n)

  • Space: O(1)

Using list comprehension

This method converts each character in the string to a separate element in the list. For example:

string = "Educative"
list = [char for char in string]
print(list) #Output: ['E', 'd', 'u', 'c', 'a', 't', 'i', 'v', 'e']

Complexity

  • Time: O(n)

  • Space: O(n)

Using the list() function

This method converts each character in the string to a separate element in the list, similar to the previous method. For example:

string = "Educative"
list = list(string)
print(list) #Output: ['E', 'd', 'u', 'c', 'a', 't', 'i', 'v', 'e']

Complexity

  • Time: O(n)

  • Space: O(n)

Using the re.findall() method

This method uses regular expressions to match all the alphabets in the string and creates a list with all the matched elements. For example:

import re
string = "ABCD"
list = re.findall('[A-Za-z]', string)
print(list) # Output: ['A', 'B', 'C', 'D']

Complexity

  • Time: O(n)

  • Space: O(n)

Using the enumerate() function

This method converts each character in the string to a separate element in the list but with lowercase letters. For example:

string = "Educative"
list = [char.lower() for _, char in enumerate(string)]
print(list) # Output: ['e', 'd', 'u', 'c', 'a', 't', 'i', 'v', 'e']

Complexity

  • Time: O(n)

  • Space: O(n)

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. For example:

def Convert(string):
list1 = []
list1[:0] = string
return list1
# Driver code
str1 = "HELLO"
print(Convert(str1))

Complexity

  • Time: O(n)

  • Space: O(n)

Any of the above-described methods can convert a string into a list.

Copyright ©2024 Educative, Inc. All rights reserved