- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
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']