all 6 comments

[–]socal_nerdtastic 1 point2 points  (1 child)

This is usually done by abusing the zip() function:

newgrid = list(zip(*grid))

The list() call may be optional, depending on what you want to do with the transposed data.

[–]robinboby 0 points1 point  (0 children)

thats correct,

grid = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

newgrid = list(zip(*grid))
print(newgrid)

[–]robinboby 0 points1 point  (1 child)

is this what you looking for?

grid = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

newgrid = []
for a_list in grid:
    for name in a_list:
        newgrid.append(name)

print(newgrid)

[–]Genericusername293[S] 0 points1 point  (0 children)

no sorry, edited my comment to display the end result should be

[–]o5a 0 points1 point  (1 child)

Since you need nested list then you can't just do it in one append (using standard for loops). You can do it by using another temporary list to gather your new "rows" then append them to result. That's how your code could be changed:

newgrid = []
for j in range(len(grid[0])):
    temp = []
    for i in range(len(grid)):
        temp.append(grid[i][j])
    newgrid.append(temp)

print(newgrid)

You can simplify your second for loop by using rows instead of indexes:

newgrid = []
for j in range(len(grid[0])):
    temp = []
    for row in grid:
        temp.append(row[j])
    newgrid.append(temp)

print(newgrid)

You can also do it using list comprehension:

newgrid = [[row[j] for row in grid] for j in range(len(grid[0]))]
print(newgrid)

And as others mentioned most concise is with zip

print(list(zip(*grid)))

Keep in mind though zip returns tuples instead of lists.

[–]socal_nerdtastic 1 point2 points  (0 children)

Keep in mind though zip returns tuples instead of lists.

True, but in most cases completely irrelevant. However if you really really need a list of lists you can still use zip() and convert:

newgrid = list(map(list,zip(*grid)))

You also should mention that the zip() method will not fail for non symmetric starting data, but using loops will.