Python - Similar index elements Matrix
Last Updated :
21 Apr, 2023
Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain ways in which this task can be performed.
Method #1: Using zip() + map()The combination of above functions can be used to perform this task. In this, we pair up lists using zip() and then using map() the construction of matrix occurs from the paired up lists.
Python3
# Python3 code to demonstrate
# Similar index elements Matrix
# using zip() + map()
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Similar index elements Matrix
# using zip() + map()
res = []
res += map(list, zip(test_list1, test_list2, test_list3))
# printing result
print ("The matrix after cummulation is : " + str(res))
OutputThe original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cummulation is : [[3, 1, 7], [4, 2, 9], [5, 6, 8]]
Method #2: Using list comprehension + zip()This is yet another way in which this task can be performed. In this, we perform the task of map() in above with the help of list comprehension.
Python3
# Python3 code to demonstrate
# Similar index elements Matrix
# using zip() + list comprehension
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Similar index elements Matrix
# using zip() + list comprehension
res = [list(sub) for sub in zip(test_list1, test_list2, test_list3)]
# printing result
print ("The matrix after cummulation is : " + str(res))
OutputThe original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cummulation is : [[3, 1, 7], [4, 2, 9], [5, 6, 8]]
Method #3: Using numpy
Python3
# Python3 code to demonstrate
# Similar index elements Matrix
# using numpy library
import numpy as np
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Similar index elements Matrix
# using numpy library
res = np.column_stack((test_list1, test_list2, test_list3))
# printing result
print("The matrix after cumulation is : \n" + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output:
The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is :
[[3 1 7]
[4 2 9]
[5 6 8]]
Time complexity: O(n)
Auxiliary Space: O(n)
Explanation: In this approach, we use the numpy library which provides us the column_stack function. This function takes a tuple of 1D arrays as input and returns a 2D array. The input arrays are stacked as columns in the output array, which results in the formation of a matrix with similar index elements.
Method 4: Using a simple for loop
- Create empty list res to store the result.
- Iterate over the indices of the lists using range(len(list)).
- For each index i, create a new empty list row to store the elements at index i from all the given lists.
- Append the element at index i from each list to row.
- Append the completed row to res.
- After iterating through all indices, the res list will contain the required matrix
Python3
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Using for loop
res = []
for i in range(len(test_list1)):
row = []
row.append(test_list1[i])
row.append(test_list2[i])
row.append(test_list3[i])
res.append(row)
# printing result
print("The matrix after cumulation is : ")
for row in res:
print(row)
OutputThe original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is :
[3, 1, 7]
[4, 2, 9]
[5, 6, 8]
Time complexity: O(n^2), where n is the length of each list. Since we are iterating over each element of the list and appending it to a new list, the time complexity will be O(n^2).
Auxiliary space: O(n^2), since we are creating a new list to store the matrix.
Method 5: Using pandas DataFrame
The pandas library can be used to create a DataFrame from the input lists and then transpose the DataFrame to obtain the desired matrix.
Step-by-step approach:
- Importing the pandas library using the "import" statement and assigning an alias "pd".
- Initializing three lists named "test_list1", "test_list2", and "test_list3" containing some integer values.
- Creating a DataFrame object by passing a dictionary of lists containing the input lists as values, and using column names as keys.
- Transposing the DataFrame to obtain the desired matrix. Transposing the DataFrame converts rows to columns and vice versa.
- Converting the transposed DataFrame to a nested list using the ".values.tolist()" method of the DataFrame object.
- Printing the result using the "print()" statement, along with a message.
- Using a "for" loop to iterate through each row of the resulting nested list, and printing each row using the "print()" statement.
Below is the implementation of the above approach:
Python3
import pandas as pd
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# Creating a DataFrame from the input lists
df = pd.DataFrame({'list1': test_list1, 'list2': test_list2, 'list3': test_list3})
# Transposing the DataFrame to obtain the desired matrix
res = df.values.tolist()
# Printing the result
print("The matrix after cumulation is : ")
for row in res:
print(row)
Output:
The matrix after cumulation is :
[3, 1, 7]
[4, 2, 9]
[5, 6, 8]
Time complexity: O(n), where n is the length of the input lists.
Auxiliary space: O(n), for creating the DataFrame.
Method 6: Using itertools:
Algorithm:
- Create an empty matrix (2D list) with dimensions equal to the number of columns of the input matrix and the number of rows equal to the length of any row of the input matrix.
- Iterate over the input matrix and insert the elements into the empty matrix at the appropriate positions.
- Return the transposed matrix.
Python3
import itertools
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
# Creating the matrix using itertools.zip_longest()
matrix = list(itertools.zip_longest(test_list1, test_list2, test_list3))
# Printing the original lists and the resulting matrix
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
print("The matrix after cumulation is : ")
for row in matrix:
print(row)
#This code is contributed by Jyothi pinjala.
OutputThe original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is :
(3, 1, 7)
(4, 2, 9)
(5, 6, 8)
Time complexity:
Let's assume the input matrix has m rows and n columns. The first step of creating the empty matrix takes O(nm) time. The second step of iterating over the input matrix and inserting elements into the empty matrix takes O(mn) time. Finally, transposing the matrix takes O(nm) time. Therefore, the overall time complexity is O(mn).
Space complexity:
The space complexity of this algorithm is also O(mn), as we need to create an empty matrix of size mxn to store the transposed matrix.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read