- Trending Categories
- 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
Python - To Convert Matrix to String
When it is required to convert a matrix into a string, a simple list comprehension along with the ‘join’ method is used.
Example
Below is a demonstration of the same
my_list = [[1, 22, "python"], [22, "is", 1], ["great", 1, 91]] print("The list is :") print(my_list) my_list_1, my_list_2 = ",", " " my_result = my_list_2.join([my_list_1.join([str(elem) for elem in sub]) for sub in my_list]) print("The result is :") print(my_result)
Output
The list is : [[1, 22, 'python'], [22, 'is', 1], ['great', 1, 91]] The result is : 1,22,python 22,is,1 great,1,91
Explanation
A list of list is defined and is displayed on the console.
Two variables are assigned to a comma and an empty space respectively.
The list comprehension and ‘join’ method is used to iterate through the list and join the elements in two variables.
This is assigned to a variable.
This is the output that is displayed on the console.
Advertisements