TheRIProgrammer
TheRIProgrammer

Reputation: 87

Creating arrays with for and while loops - Python 2

I have the following program which successfully creates a 10x20 array filled with zeros:

array2 = []
array2=[[0 for j in range(10)] for i in range(20)]
print array2

I then tried to do the same with a for loop and a while loop:

for j in range(20):
  for i in range(10):
    array1.append(0)
print array1

array3 = []
count = 0
while count <= 20:
  count += 1
  while count <= 10:
    array3.append(0)
    count += 1
print array3

I feel like I am on the right track, but I can not seem to be able to create the same thing with these loops. How can I tweak these loops in order to create the same effect as the first one? Thank you.

Upvotes: 1

Views: 19649

Answers (3)

Rolf Lussi
Rolf Lussi

Reputation: 615

In the first one you add the arrays of length 10 to the bigger array. So you need to create two arrays.

array1 = []
array2 = []
for j in range(20):
    for i in range(10):
        array1.append(0)
    array2.append(array1)
    array1 = []
print array2

This is equivalent to

array2=[[0 for j in range(10)] for i in range(20)]

Upvotes: 5

schafle
schafle

Reputation: 613

You need to create a temporary list inside outer for/while loop which you can fill inside inner for/while loop.

First:

>>> for j in range(20):
...     temp=[]
...     for i in range(10):
...             temp.append(0)
...     array1.append(temp)
...
>>> array1

Second:

>>> count=0
>>> array3=[]
>>> while count < 20:
...     temp=[]
...     count_inner=0
...     count+=1
...     while count_inner< 10:
...             temp.append(0)
...             count_inner+=1
...     array3.append(temp)
>>> array3

With your conditions in while loop check you were creating 21 X 11 matrix.

Upvotes: 2

Chris Nantau
Chris Nantau

Reputation: 38

In your first example you've got an array of arrays. If you look at the line you can see that you've got [[] <-- internal array] <---outer array.

in your other arrays you're just creating a really long array of zeros through appends. the equivalent with for loops would be something along the lines of:

arr = []

for i in range(20):
    arr.append([])
    for j in range(10):
        arr[i].append(0)

for thing in arr:
    print thing

Upvotes: 1

Related Questions