Skip to content
Related Articles

Related Articles

Improve Article
Python – Extract String elements from Mixed Matrix
  • Last Updated : 01 Oct, 2020

Given a Matrix, Extract all the elements that are of string data type.

Input : test_list = [[5, 6, 3], [“Gfg”, 3], [9, “best”, 4]] 
Output : [‘Gfg’, ‘best’] 
Explanation : All strings are extracted.

Input : test_list = [[“Gfg”, 3], [9, “best”, 4]] 
Output : [‘Gfg’, ‘best’] 
Explanation : All strings are extracted. 

Method #1 : Using list comprehension + isinstance()

The combination of above functions can be used to solve this problem. In this, we iterate nested lists using list comprehension and check for string instance using isinstance().



Python3




# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# Using list comprehension + isinstance()
  
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
  
# printing original list
print("The original list : " + str(test_list))
  
# strings are extracted using isinstance()
res = [ele for sub in test_list for ele in sub if isinstance(ele, str)]
  
# printing result
print("The String instances : " + str(res))
Output
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']


Method #2 :  Using chain.from_iterables() + list comprehension + isinstance()

This is yet another way in which this task can be performed. Whole Matrix is flattened and then isintance() is applied over it to check for string elements in flattened list.

Python3




# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# Using chain.from_iterables + list comprehension + isinstance()
from itertools import chain
  
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
  
# printing original list
print("The original list : " + str(test_list))
  
# strings are extracted using isinstance()
# using chain.from_iterables()
res = [ele for ele in chain.from_iterable(test_list) if isinstance(ele, str)]
  
# printing result
print("The String instances : " + str(res))
Output
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :