Best way to do this? List loop (matrix?) iteration

Chris Angelico rosuav at gmail.com
Tue Jan 8 21:06:05 EST 2013


On Wed, Jan 9, 2013 at 11:19 AM,  <andydtaylor at gmail.com> wrote:
>    stn_count = len(stn_list_short)
>    for rowcount in range (0, stn_count):
>       for colcount in range (0, stn_count):
>          print stn_list_long[rowcount] stn_list_long[colcount]

First off, you can iterate over the list directly:

for row in stn_list_short:
  for col in stn_list_short:
    print row + col

(I'm not sure what your code was doing with the print line, because it
ought to have failed. Explicit concatenation will work.)

Secondly, you can make a list of all of those pairs with a compact
notation called a comprehension:

pairs = [row + col for row in stn_list_short for col in stn_list_short]

That covers your requirement #2, giving you a full list of all of
them. How big is k going to be? Storing the whole list in memory will
get a little awkward if you have very large k; on this system, I
started seeing performance issues with a thousand elements in the
list, but you could probably go to ten thousand (ie a hundred million
pairs) if you have a decent bit of RAM.

ChrisA



More information about the Python-list mailing list