Learnitweb

How to split a string into an list of characters in Python?

We’ll discuss following ways to convert string into an array of characters:

  1. Using list constructor
  2. Using list comprehension
  3. Using map and lambda
  4. Using for loop
  5. Unpacking into an empty list
  6. Using extend() method

Method 1: Using list constructor

The list constructor takes a single argument which is iterable. You can pass a sequence, collection or an iterator object.

word = 'hello world'
l = list(word)
print(l)

Output

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

Method 2: Using list comprehension

List comprehension offers a shorter syntax to create a list of characters.

word = 'hello world'
l = [x for x in word]
print(l)

Method 3: Using map and lambda

In this code, lambda is used to get one character at a time. The lambda keyword is used to define an anonymous function in Python. map() takes two arguments, first is the function and second a sequence. map() applies to function to all elements of the sequence. In the end, we collect elements in list.

word = 'hello world'
l = list(map(lambda ch: ch, word))
print(l)

Method 4: Using for loop

This is a very basic approach and not recommended to use for this problem. In this code, we get one character at a time and append it to the list.

# initialize string
word = 'hello world'

# create empty string
l = []

# get each character using for loop
for character in word:
    l.append(character)

# print list
print(l)

Method 5: Unpacking list into an empty list

This is one of the shortest syntax but less known.

# initialize string
word = 'hello world'

# using unpacking to create list
l = [*word]

print(l)

Method 6: Using extend method

The extend() method adds all the elements of an iterable to the end of the list. In this code we use an empty list and use it with extend() method to get desired result.

# initialize string
word = 'hello world'

#create empty list to hold result
l = []

# use extend method to add elements of iterable to the empty list
l.extend(word)

# print list
print(l)