How to Split a String into a List in Python

To turn a string into a list (array) in Python, we can use the split() method. split() breaks up a string by a specified separator and works in a similar way to functions for creating arrays in other programming languages like explode() in PHP and split() in JavaScript.

 

The split() Syntax

split() takes two arguments, the first is the separator (delimiter) to split the string by and the second is the maximum of splits to perform on the string. 

 

string.split([separator, [limit]])

 

split() returns a list that can be stored in a variable.

 

Split Each Character in the String

To create a list with every character from the string being an element, create a for loop to iterate through the string and append each value to an array.

 

string = 'SkillSugar'

items = []

for i in string:
    items.append(i)

print(items)
['S', 'k', 'i', 'l', 'l', 'S', 'u', 'g', 'a', 'r']

 

Turn the Whole String into One list Element

To turn the whole string into one element in a list, pass an empty separator in the splt() method.

 

string = 'SkillSugar'

items = string.split()

print(items)
['SkillSugar']

 

Split a Comma Separated String

Let's say we had a string of items separated by commas. Each item could be split into a list element by using (comma and space) as the separator.

 

fruit = 'apple, strawberry, apricot, orange'

items = fruit.split(', ')

print(items)
['apple', 'strawberry', 'apricot', 'orange']

 

Limit the Number of Splits to Make

To limit the number of splits performed pass the maximum number as the second argument of split(). When the limit has been reached the rest of the string is put into a single element at the end of the list.

 

fruit = 'apple, strawberry, apricot, orange'

items = fruit.split(', ', 2)

print(items)
['apple', 'strawberry', 'apricot, orange']

 

Conclusion

You now know how to split a string into a list in Python. The example above demonstrated splitting a comma-separated string, but it is possible to use any substring.

string split list array