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 [ ].
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
split()
methodThis 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)
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)
list()
functionThis 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)
re.findall()
methodThis method uses regular expressions to match all the alphabets in the string and creates a list with all the matched elements. For example:
import restring = "ABCD"list = re.findall('[A-Za-z]', string)print(list) # Output: ['A', 'B', 'C', 'D']
Complexity
Time: O(n)
Space: O(n)
enumerate()
functionThis 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)
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] = stringreturn list1# Driver codestr1 = "HELLO"print(Convert(str1))
Complexity
Time: O(n)
Space: O(n)
Any of the above-described methods can convert a string into a list.