How to define a 2-D array without an initialized length, something like this: A = [][]
Apr 15, 2018 in Python 1,019 views

You can use NumPy library of Python, below I have mentioned few ways to create 2-D arrays using NumPy:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!

>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor

• 3,440 points
```>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.]])```
answered Oct 18, 2018 by rishav
```>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]```
answered Oct 18, 2018 by pinre

You should make a list of lists, and the best way is to use nested comprehensions:

```>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]```
answered Oct 18, 2018 by ritu

How do I trim extra zeros from a 2D array in python?

Hey @Laksha, you can try something like ...READ MORE

Error in Python script "Expected 2D array, got 1D array instead:"?

I wanted to make this ML prediction ...READ MORE

+1 vote

How to print array/ list without brackets in python?

print(*names, sep = ', ') This is what ...READ MORE

How to slice an array using python numpy? Is there any numpy tutorial which has covered all its operations?

Slicing is basically extracting particular set of ...READ MORE

how do i change string to a list?

suppose you have a string with a ...READ MORE

how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE