0

Example:

array[0] = [item1,item2]
array[1] = [item1,item2]
array[2] = [item1,item2]
array[3] = [item1,item2]

How to create a array like this in python?

2
  • 1
    Are the items all going to be the same type? If all your item1s and item2s are going to be of the same type, you just want a 2D array. Commented Jan 3, 2014 at 12:45
  • Also, are you actually using numpy? It's not clear from your original question whether you're actually using numpy arrays, or whether the tag is a mistake. Commented Jan 3, 2014 at 12:51

2 Answers 2

1

There are at least two ways which look similar but are actually quite different:

The first way is to create a two dimensional array:

import numpy as np

foo = np.array([[0,1],[2,3],[4,5],[6,7]])
# foo = np.arange(4*2).reshape(4,2)   # this does the same thing
print(foo[0])    # the first row of `foo`
# [0 1]

print(foo[1])    # the second row of `foo`
# [2 3]

The second way is to create a one-dimensional array of dtype 'object', where the objects are Python lists:

bar = np.empty(4, dtype='object')
bar[0] = [0,1]
bar[1] = [2,3]
bar[2] = [4,5]
bar[3] = [6,7]

print(bar[0])
# [0, 1]

print(bar[1])
# [2, 3]

Note that in the first example, foo[0] is a NumPy array. In the second example, bar[0] is a Python list.

Numerical calculations done on foo will tend to be much quicker than similar operations done on bar. If the items stored in the Python lists are numeric and/or of a homogenous type (such as all strings), using a higher-dimensional NumPy array tends to be better choice than a NumPy array of dtype object. (Especially for numeric data, not only are there speed benefits to using homogenous arrays of non-object dtypes, but moreover, some NumPy functions do not work on arrays of object dtype.)

Sign up to request clarification or add additional context in comments.

Comments

0

What type are 'item1' and 'item2'? Also are they the same type? See the example below.

your_array = [[5,3], [3,6], [4, 9]] # you could do this
print(your_array[0]) # would print [5,3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.