List loops

Tim Chase python.list at tim.thechases.com
Tue Oct 9 11:27:42 EDT 2007


>  >>> alist = range(3)
>  >>> for i in xrange(len(alist)):
> ...   for j in xrange(i+1,len(alist)):
> ...     print i,j,alist[i],alist[j]
> ...
> 0 1 0 1
> 0 2 0 2
> 1 2 1 2
>  >>>
> 
> 
> Is there a way to do this without using indexes?

The following works for me, replicating your code,

 >>> alist = range(3)
 >>> for i, itemA in enumerate(alist):
...     for j, itemB in enumerate(alist[i+1:]):
...             print i,j+i+1,itemA, itemB
...
0 1 0 1
0 2 0 2
1 2 1 2


and is swappable if your alist has other values in it too:

 >>> alist = ['dog', 'cat', 'mouse']
 >>> for i, itemA in enumerate(alist):
...     for j, itemB in enumerate(alist[i+1:]):
...             print i,j+i+1,itemA, itemB
...
0 1 dog cat
0 2 dog mouse
1 2 cat mouse


However, if your list only has those range() values in it, 
there's nothing wrong with doing something like

 >>> for i in alist:
...	for j in alist[i+1:]:
...		print i,j,i,j
...

It looks like you're trying to do permutations/combinations of 
things, in which case you might also find this helpful:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465


-tim








More information about the Python-list mailing list