Python – Extract String elements from Mixed Matrix
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 liststest_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]# printing original listprint("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 resultprint("The String instances : " + str(res)) |
Output
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]] The String instances : ['Gfg', 'is', 'best']
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) additional space is not needed.
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 liststest_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]# printing original listprint("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 resultprint("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 #3 : Using extend() and type() methods
Python3
# Python3 code to demonstrate working of# Extract String elements from Mixed Matrix# initializing liststest_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]# printing original listprint("The original list : " + str(test_list))x=[]res=[]for i in test_list: x.extend(i)for i in x: if(type(i) is str): res.append(i) # printing resultprint("The String instances : " + str(res)) |
Output
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]] The String instances : ['Gfg', 'is', 'best']


Please Login to comment...