0

If I have the following matrix:

m = [[1, 2, 3],
     [4, 5, 6], 
     [7, 8, 9]]

how do I return a list that looks like this

[[1, 4, 7], 
 [2, 5, 8], 
 [3, 6, 9]]

without using built-in functions?

Edit: I can use len() and range()

lilai
  • 39
  • 1
  • 5

3 Answers3

2

You can use a nested comprehension, à la:

[[row[i] for row in m] for i in range(len(m[0]))]

If the typical transpositioning idiom zip(*m) (or [*map(list, zip(*m))] if exact types matter) is to be avoided as too purpose-built.

user2390182
  • 72,016
  • 6
  • 67
  • 89
1

Weird approach:

m = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

res = map(lambda *args: args, *m)
print(list(res))

Output

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If list are required:

res = list(map(lambda *args: list(args), *m))
print(res)

Alternative:

res = [*map(lambda *args: list(args), *m)]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 1
    Very creative `zip` implementation: `zip = lambda *iterables: map(lambda *args: args, *iterables)` One does have to stare down what's happening though :D +1 – user2390182 Oct 25 '21 at 11:06
0

try this

m = [[1, 2, 3],
     [4, 5, 6], 
     [7, 8, 9]]
result=[[0 for i in range(len(m))] for j in range(len(m[0]))]
for i in range(len(m)):
    for j in range(len(m[0])):
        result[j][i]=m[i][j]
print(result)
Prasad Darshana
  • 186
  • 2
  • 14