[python] Iterating over a 2 dimensional python list

I have created a 2 dimension array like:

rows =3
columns= 2
mylist = [[0 for x in range(columns)] for x in range(rows)]
for i in range(rows):
    for j in range(columns):
        mylist[i][j] = '%s,%s'%(i,j)
print mylist

Printing this list gives an output:

[  ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1']   ]

where each list item is a string of the format 'row,column'

Now given this list, i want to iterate through it in the order:

'0,0'
'1,0'
'2,0'
'0,1'
'1,1'
'2,1'

that is iterate through 1st column then 2nd column and so on. How do i do it with a loop ?

This Question pertains to pure python list while the question which is marked as same pertains to numpy arrays. They are clearly different

This question is related to python loops multidimensional-array

The answer is


This is the correct way.

>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
        for j in range(len(x[i])):
                print(x[i][j])


0,0
0,1
1,0
1,1
2,0
2,1
>>> 

zip will transpose the list, after that you can concatenate the outputs.

In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]

>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

same way you did the fill in, but reverse the indexes:

>>> for j in range(columns):
...     for i in range(rows):
...        print mylist[i][j],
... 
0,0 1,0 2,0 0,1 1,1 2,1
>>> 

Ref: zip built-in function

zip() in conjunction with the * operator can be used to unzip a list

unzip_lst = zip(*mylist)
for i in unzip_lst:
    for j in i:
        print j

>>> mylist = [["%s,%s"%(i,j) for j in range(columns)] for i in range(rows)]
>>> mylist
[['0,0', '0,1', '0,2'], ['1,0', '1,1', '1,2'], ['2,0', '2,1', '2,2']]
>>> zip(*mylist)
[('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1'), ('0,2', '1,2', '2,2')]
>>> sum(zip(*mylist),())
('0,0', '1,0', '2,0', '0,1', '1,1', '2,1', '0,2', '1,2', '2,2')

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array