nickyfot
nickyfot

Reputation: 2019

Python will not append to list in for loop

i am basically trying to switch around an array of arrays; my initial data are:

array = [
    [0,0,0],
    [1,1,1]
    ]

the output should be:

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

however what i get is:

[]

i have tried doing the same thing without the loops but when i introduce them it just wont append!

see code here:

array = [
    [0,0,0],
    [1,1,1]
    ]
transformedArray = []
#add rows to transformed
for j in range(0, len(array) - 1):
    transformedArray.append([])
#for each row
for i in range(0, len(array[0]) - 1):
    #for each column
    for k in range(0, len(array) - 1):
        transformedArray[i].append(array[k][i])

can you help? i have not found any similar issues online so i am guessing i've missed something stupid!

Upvotes: 0

Views: 515

Answers (2)

Bob Dill
Bob Dill

Reputation: 1010

Try nesting your loops:

array = [
    [0,0,0],
    [1,1,1]
    ]
transformedArray = [[0,0],[0,0],[0,0]]

# iterate through rows
for i in range(len(array)):
   # iterate through columns
   for j in range(len(array[0])):
         transformedArray[j][i] = array[i][j]

for res in transformedArray:
     print(res)

returns:

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

Edited to Add explanation:

First, lists are defined as in this code above: aList = [ ... ] where an array would be defined as anArray = numpy.array([...]), so to the point of the comments above, this is list processing in the question, not true python array process. Next, elements are being added to the list by index, so there has to be a place to put them. I handled that by creating a list with 3 elements already in place. The original post would only create the first 2 rows and then have an index failure when the 3rd row is to be created. The nested for loops then iterate through the embedded lists.

Upvotes: 1

Alex
Alex

Reputation: 790

You could do it by mapping a sequence of index-access operations over all the arrays:

for i in range( len( array[0] ) ):
    transformedArray.append( map( lambda x: x[i], array ) )

Upvotes: 0

Related Questions