Split a word into a list of letters in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a word into a list of letters in Python #

Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str). The list() class will convert the string into a list of letters.

main.py
my_str = 'hello' my_list = list(my_str) # 👇️ ['h', 'e', 'l', 'l', 'o'] print(my_list)

The list class takes an iterable and returns a list object.

When a string is passed to the class, it splits the string on each character and returns a list containing the characters.

An alternative approach is to use a list comprehension.

Use a list comprehension to split a word into a list of letters, e.g. my_list = [letter for letter in my_str]. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

main.py
my_str = 'hello' my_list = [letter for letter in my_str] # 👇️ ['h', 'e', 'l', 'l', 'o'] print(my_list)

You can also filter letters out of the final list when using this approach.

main.py
my_str = 'h e l l o' my_list = [letter for letter in my_str if letter.strip()] # 👇️ ['h', 'e', 'l', 'l', 'o'] print(my_list)

The string in the example has spaces.

Instead of getting list items that contain a space, we call the strip() method on each letter and see if the result is truthy.

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

If the string stores a space, it would get excluded from the final list.

You can also use a simple for loop to split a word into a list of letters.

main.py
my_str = 'hello' my_list = [] for letter in my_str: my_list.append(letter) # 👇️ ['h', 'e', 'l', 'l', 'o'] print(my_list)

We used a for loop to iterate over the string and use the append method to add each letter to the list.

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

You can also conditionally add the letter to the list.

main.py
my_str = 'hello' my_list = [] for letter in my_str: if letter.strip() != '': my_list.append(letter) # 👇️ ['h', 'e', 'l', 'l', 'o'] print(my_list)

The string is only added to the list if it isn't a space.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.