0

I have the following nested list:

grid = [[a, b, c, d, e],
        [f, g, h, i, j],
        [k, l, m, o, p]]

And in a for loop, I want to take the nth element of each sublist and append it to a single, 1-dimension list. So at the first iteration, it'll look like this:

[a, f, k]

and the next iteration, it'll look like this:

[b, g, l]

and so on.

I want to do this just because I want to create this list to another existing, constant list. The following is my attempt but what it does is that it only creates a vertical list of the last element of each sublist:

for j in range(0, len(grid)):
        column_list = [item[j] for item in grid] 
Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • @VishalSingh no because the user is trying to create a new nested list, I'm not. Also their problem is that their new nested list becomes tuples. – Onur-Andros Ozbek Oct 08 '20 at 05:29
  • Shouldn't the first iteration look like `[a, f, k]` ? – Shivam Jha Oct 08 '20 at 05:40
  • It should be straightforward enough to tweak the answers in the linked duplicate/in the answers already given below to not create a new nested list. If you run into any trouble doing this, I recommend asking a new question focusing on that specific part of the problem. – Michael0x2a Oct 08 '20 at 18:39

3 Answers3

1

Below should do it:

list_ = [['a',' b', 'c', 'd', 'e'],
        ['f', 'g','h', 'i', 'j'],
        ['k', 'l', 'm',' o', 'p']]

[list(tup) for tup in zip(*list_)]

This will produce:

[['a', 'f', 'k'],
 [' b', 'g', 'l'],
 ['c', 'h', 'm'],
 ['d', 'i', ' o'],
 ['e', 'j', 'p']]
Dev
  • 665
  • 1
  • 4
  • 12
0

Easiest method is to use numpy:

grid = np.array(grid)
print (grid[:, 0]) # a, f, k
print (grid[:, 1]) # b, g, l

Iterating through grid:

data = [grid[:, i] for i in range(len(grid[0]))]

You could just add:

data = [list(grid[:, i]) for i in range(len(grid[0]))]

if it definitely has to be a list of lists.

nnarenraju
  • 11
  • 2
0

NESTED LOOP

You can just do it easily with nested loops :

list = [['a', 'b', 'c', 'd', 'e'],
        ['f', 'g', 'h', 'i', 'j'],
        ['k', 'l', 'm', 'o', 'p']]
i=0
j=0
while(j < len(list[0])):
    i=0
    vert =[]
    while ( i < len(list)):
        vert.append(list[i][j])
        i += 1
    j +=1
    print(vert)

The Outpus is :

['a', 'f', 'k']
['b', 'g', 'l']
['c', 'h', 'm']
['d', 'i', 'o']
['e', 'j', 'p']
Hosseinreza
  • 561
  • 7
  • 18