Convert list of strings and characters to list of characters in Python


While dalign with lists, we may come across a situation where we have to process a string and get its individual characters for further processing. In this article we will see various ways to do that.

With list comprehension

We design a for loop to go through each element of the list and another loop inside this to pick each character from the element which is a string.

Example

 Live Demo

listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = [i for ele in listA for i in ele]
# Result
print("List of characters: \n",res)

Output

Running the above code gives us the following result −

Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']

With chain

The itertools module of python gives us the chain function. Using it we fetch each character from the strings of the list and put it into a new list.

Example

 Live Demo

from itertools import chain
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = list(chain.from_iterable(listA))
# Result
print("List of characters: \n",res)

Output

Running the above code gives us the following result −

Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']

With join

The join method can be used to combine all the elements into a single string and then apply the list function which will store each character as a separate string.

Example

 Live Demo

listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = list(''.join(listA))
# Result
print("List of characters: \n",res)

Output

Running the above code gives us the following result −

Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']

Updated on: 20-May-2020

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements