Sie sind auf Seite 1von 4

Two dimensional array in python - Stack Overow http://stackoverow.com/questions/8183146/two-...

sign up log in tour help stack overow careers

Stack Overow is a question and answer site for professional and enthusiast programmers. It's 100% free. Take the 2-minute tour

Two dimensional array in python

I want to know how to declare a two dimensional array in Python.

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

The rst two assignments work ne. But when I try to do, arr[1].append("bb1"), I get the
following error,

IndexError: list index out of range.

Am I doing anything silly in trying to declare the 2-D array

[edit]: but i do not know the no. of elements in the array (both rows and columns).

python multidimensional-array

edited Nov 18 '11 at 13:37 asked Nov 18 '11 at 13:28


SyncMaster
2,333 17 54 92

8 Answers

You do not "declare" arrays or anything else in python. You simply assign to a (new) variable. If
you want a multidimensional array, simply add a new array as an arary element.

arr = []
arr.append([])
arr[0].append('aa1')
arr[0].append('aa2')

or

arr = []
arr.append(['aa1', 'aa2'])

edited Nov 18 '11 at 13:39 answered Nov 18 '11 at 13:30


ThiefMaster
157k 31 269 372

2 Shouldn't this be arr.append(...) instead of arr[0] = ... , to avoid IndexError: list


assignment index out of range ? Bruno Nov 18 '11 at 13:37

1 yeah, xed it. ThiefMaster Nov 18 '11 at 13:39

There aren't multidimensional arrays as such in Python, what you have is a list containing other
lists.

>>> arr = [[]]


>>> len(arr)
1

What you have done is declare a list containing a single list. So arr[0] contains a list but
arr[1] is not dened.

You can dene a list containing two lists as follows:

1 of 4 Saturday 18 July 2015 01:22 AM


Two dimensional array in python - Stack Overow http://stackoverow.com/questions/8183146/two-...

arr = [[],[]]

Or to dene a longer list you could use:

>>> arr = [[] for _ in range(5)]


>>> arr
[[], [], [], [], []]

What you shouldn't do is this:

arr = [[]] * 3

As this puts the same list in all three places in the container list:

>>> arr[0].append('test')
>>> arr
[['test'], ['test'], ['test']]

edited Nov 18 '11 at 13:38 answered Nov 18 '11 at 13:33


Dave Webb
104k 28 221 253

What does the underscore in the list comprehension do? Kris Harper Nov 18 '11 at 13:55

1 @root45 We need a variable in the list comprehension so we could put arr = [[] for i in range(5)]
but there is a convention to name a variable you're never going to use as _ . Although in the interactive
Python REPL the _ variable stores the result of the last expression. Dave Webb Nov 18 '11 at 13:59

What you're using here are not arrays, but lists (of lists).

If you want multidimensional arrays in Python, you can use Numpy arrays. You'd need to know
the shape in advance.

For example:

import numpy as np
arr = np.empty((3, 2), dtype=object)
arr[0, 1] = 'abc'

answered Nov 18 '11 at 13:40


Bruno
58.4k 5 95 168

you statement can be also much simpler written as

arr = [
["aa1", "aa2"],
["bb1", "bb2", "bb3"]
]

answered Nov 18 '11 at 13:37


georg
67.6k 10 85 156

2 of 4 Saturday 18 July 2015 01:22 AM


Two dimensional array in python - Stack Overow http://stackoverow.com/questions/8183146/two-...

You try to append to second element in array, but it does not exist. Create it.

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr.append([])
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

edited Nov 18 '11 at 13:41 answered Nov 18 '11 at 13:34


tony
822 15 21

a = [[] for index in range(1, n)]

edited Nov 23 '12 at 8:42 answered Nov 23 '12 at 7:10


akjoshi user306080
7,588 12 52 92 358 5 17

When constructing multi-dimensional lists in Python I usually use something similar to


ThiefMaster's solution, but rather than appending items to index 0 , then appending items to
index 1 , etc., I always use index -1 which is automatically the index of the last item in the
array.

i.e.

arr = []

arr.append([])
arr[-1].append("aa1")
arr[-1].append("aa2")

arr.append([])
arr[-1].append("bb1")
arr[-1].append("bb2")
arr[-1].append("bb3")

will produce the 2D-array (actually a list of lists) you're after.

answered Dec 30 '12 at 17:52


Lurchman
41 4

We can create multidimensional array dynamically as follows,

Create 2 variables to read x and y from standard input:

print("Enter the value of x: ")


x=int(input())

print("Enter the value of y: ")


y=int(input())

Create an array of list with initial values lled with 0 or anything using the following
code

z=[[0 for row in range(0,x)] for col in range(0,y)]

creates number of rows and columns for your array data.

Read data from standard input:

for i in range(x):
for j in range(y):
z[i][j]=input()

Display the Result:

3 of 4 Saturday 18 July 2015 01:22 AM


Two dimensional array in python - Stack Overow http://stackoverow.com/questions/8183146/two-...

for i in range(x):
for j in range(y):
print(z[i][j],end=' ')
print("\n")

or use another way to display above dynamically created array is,

for row in z:
print(row)

answered Aug 25 '14 at 10:24


PUNITH
41 4

4 of 4 Saturday 18 July 2015 01:22 AM

Das könnte Ihnen auch gefallen