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?

A__
  • 1,616
  • 2
  • 19
  • 33
  • 6
    Before someone suggests `[[0, 1]]*NUM_ITEMS`, [no, that doesn't work, even if it looks like it does](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly). – user2357112 Nov 20 '18 at 22:09

2 Answers2

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]]
chris
  • 1,915
  • 2
  • 13
  • 18
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]])
timgeb
  • 76,762
  • 20
  • 123
  • 145