Skip to content
Related Articles

Related Articles

Python – Extract String elements from Mixed Matrix

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 07 Feb, 2022

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 isinstance() 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']


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!