Python - Extract String elements from Mixed Matrix
Last Updated :
30 Apr, 2023
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))
OutputThe 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 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))
OutputThe 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 lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("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 result
print("The String instances : " + str(res))
OutputThe original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']
Method #4: Using nested loops
- Initialize an empty list res.
- Loop through each sublist in test_list.
- For each sublist, loop through each element.
- Check if the element is a string using isinstance() function.
- If the element is a string, append it to the res list.
- Finally, print the res list.
Python3
# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
res = []
for sublist in test_list:
for element in sublist:
if isinstance(element, str):
res.append(element)
# printing result
print("The String instances : " + str(res))
OutputThe original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']
Time complexity: O(n^2) where n is the length of test_list.
Auxiliary space: O(m) where m is the number of string elements in the list.
Method #5 : Using reduce():
Algorithm :
- Initialize a 2D list named test_list containing three sublists, each with a mix of integer and string elements.
- Print the original list.
- Initialize an empty list named res to store the string elements.
- Iterate over each sublist in test_list.
- For each sublist, iterate over each element.
- If the element is a string, append it to the res list.
- After all elements have been checked, return the res list containing all string elements.
- Print the resulting list of string elements.
Python3
from functools import reduce
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
# using reduce() to extract string elements
res = reduce(lambda acc, sublist: acc + [elem for elem in sublist if isinstance(elem, str)], test_list, [])
# printing result
print("The String instances : " + str(res))
#This code is contributed by Rayudu
OutputThe original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']
The time complexity : O(n*m) where n is the number of sublists in test_list and m is the length of the longest sublist. This is because we are iterating over each element of each sublist using the nested for loops, and the isinstance() function has a constant time complexity.
The space complexity : O(m) because we are creating a new list to store the resulting string elements, and the size of this list is proportional to the number of string elements in the matrix.
Method #6 : Using heapq:
Algorithm :
- Initialize an empty list res to store the string elements.
- Use a list comprehension to iterate over each sublist in the input list.
- Filter the string elements from each sublist using filter() and a lambda function that checks if an element is an instance of a string.
- Merge the filtered sublists using heapq.merge() to create an iterator that yields the string elements in ascending order.
- Convert the iterator to a list using list().
- Store the resulting list of string elements in the res list.
- Return the res list.
Python3
import heapq
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
# using heapq to extract string elements
res = list(heapq.merge(*[filter(lambda x: isinstance(x, str), sublist) for sublist in test_list]))
# printing result
print("The String instances : " + str(res))
#This code is contributed by Vinay pinjala.
OutputThe original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'best', 'is']
Time Complexity:
The time complexity of this algorithm is O(NlogN), where N is the total number of elements in the input list. This is because the heapq.merge() method uses a heap data structure that requires O(logN) time to insert and extract elements, and it is performed on each sublist.
Space Complexity:
The space complexity of this algorithm is O(N), where N is the total number of elements in the input list. This is because the filter() method creates a new list of filtered elements for each sublist in the input list, and the resulting list of string elements is stored in the res list.
Similar Reads
Get column names from CSV using Python
CSV (Comma Separated Values) files store tabular data as plain text, with values separated by commas. They are widely used in data analysis, machine learning and statistical modeling. In Python, you can work with CSV files using built-in libraries like csv or higher-level libraries like pandas. In t
2 min read
Python sympy | Matrix.columnspace() method
With the help of sympy.Matrix().columnspace() method, we can find the Columnspace of a Matrix. Matrix().columnspace() returns a list of column vectors that span the columnspace of the matrix. Syntax: Matrix().columnspace() Returns: Returns a list of column vectors that span the columnspace of the ma
1 min read
How to Make an Email Extractor in Python?
In this article, we will see how to extract all the valid emails in a text using python and regex. A regular expression shortened as regex or regexp additionally called a rational expression) is a chain of characters that outline a seek pattern. Usually, such styles are utilized by string-looking al
3 min read
Python | Numpy matrix.tostring()
With the help of Numpy matrix.tostring() method, we can find the byte code in string format for the matrix by using the matrix.tostring() method. Syntax : matrix.tostring() Return : Return byte code string for matrix Example #1 : In this example we can see that by using matrix.tostring() method we a
1 min read
Python | sympy.Matrix.col() method
With the help of sympy.Matrix().col() method, we can extract the columns of the matrix. Syntax : sympy.Matrix().col() Return : Return the col of a matrix. Example #1 : In the given example we can see that the sympy.Matrix.col() method is used to extract the columns of a matrix. Python3 1=1 # Import
1 min read
Pandas Extracting rows using .loc[] - Python
Pandas provide a unique method to retrieve rows from a Data frame. DataFrame.loc[] method is a method that takes only index labels and returns row or dataframe if the index label exists in the caller data frame. To download the CSV used in code, click here.Example: Extracting single Row In this exam
3 min read
Extracting rows using Pandas .iloc[] in Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. here we are learning how to Extract rows using Pandas .iloc[] in Python.Pandas .iloc[
7 min read
Split a string on multiple delimiters in Python
In this article, we will explore various methods to split a string on multiple delimiters in Python. The simplest approach is by using re.split().Using re.split()The re.split() function from the re module is the most straightforward way to split a string on multiple delimiters. It uses a regular exp
2 min read
How to extract the data from an ImmutableMultiDict
Perquisites : ImmutableMultiDict In this article, we are going to use ImmutableMultiDict to extract the data using Python, which is a type of Dictionary in which a single key can have different values. It is used because some form elements have multiple values for the same key and it saves the multi
1 min read
Python - Converting list string to dictionary
Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val
3 min read