4

Using the following method:

myArray = [0,1] * NUM_ITEMS

Desired result (2d array):

[[0,1],[0,1],[0,1]...]

Actual result (extended 1d array):

[0,1,0,1,0,1...]

How can I achieve the desired result preferably without using numpy?

asked Nov 20, 2018 at 22:07
1

2 Answers 2

5

A list comprehension should do the trick:

>>> NUM_ITEMS = 5
>>> my_array = [[0, 1] for _ in range(NUM_ITEMS)]
>>> my_array
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
answered Nov 20, 2018 at 22:08
Sign up to request clarification or add additional context in comments.

Comments

1

Since you tagged arrays, here's an alternative numpy solution using numpy.tile.

>>> import numpy as np
>>> NUM_ITEMS = 10
>>> np.tile([0, 1], (NUM_ITEMS, 1))
array([[0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1],
 [0, 1]])
answered Nov 20, 2018 at 22:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.