Python Forum

Full Version: converting list of zero length to a matrix of 3*3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a list (length of a list is one) [[1,2,3],[4,5,6]], I like to convert it to a matrix (2*3). something like this [1 2 3 
      4 5 6]

This is an example of a real problem, therefore not putting my large code here. Thanks
The example is a list of 2, with each element having 3. That said, you want to flatten the list to be 1 by 6.
mylist = [[1,2,3],[4,5,6]]
flatlist = [item for sublist in mylist for item in sublist]
print(flatlist)
Output:
[1, 2, 3, 4, 5, 6]
There is no such thing as a Python matrix. You can have a list of lists, like you show in your example. If you are using numpy you can have an array of arrays.
m = np.array([[1, 2, 3], [4, 5, 6]))
m can have matrix like things done to it like m.transpose() or m.dot(anotherM)

There used to be a matrix class in numpy, but I think it is depreciated.