<div>One of the advantages of using itertools is that it is written in C rather than Python (at least for CPython) and thus should run significantly faster than a pure Python implementation.</div><br clear="all">Chris<br>
<br><br><div class="gmail_quote">On Mon, Sep 20, 2010 at 4:21 PM, Dave Angel <span dir="ltr"><<a href="mailto:davea@ieee.org">davea@ieee.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div><div></div><div class="h5"> On 2:59 PM, Seth Leija wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
I need to know how to generate a list of combinations/permutations<br>
(can't remember which it is). Say I have a list of variables:<br>
<br>
[a,b,c,d,...,x,y,z]<br>
<br>
I am curious if there is an optimized way to generate this:<br>
<br>
[[a,b],[a,c],[a,d],...,[x,z],[y,z]]<br>
<br>
I currently have an iteration that does this:<br>
<br>
#list.py<br>
<br>
from math import *<br>
<br>
list1=['a','b','c','d','e']<br>
list2=[]<br>
length=len(list1)<br>
<br>
for it1 in range(0 ,length):<br>
for it2 in range(it1+1, length):<br>
list2.append([list1[it1],list1[it2]])<br>
<br>
print list2<br>
<br>
However, this is one of the slowest parts of my function (beaten only<br>
by variable instantiation). I posted this on another forum looking to<br>
see if there was a different method completely. They said that my<br>
method was about as simple as it could get, but I might be able to<br>
find out how to optimize my code here.<br>
<br>
Thanks in advance.<br>
<br>
</blockquote></div></div>
You're apparently looking for combinations. You're asking for all the combinations of items from the original list, taken two at a time.<br>
<br>
Permutations would also include the reverse of each item, so it would be exactly twice the size.<br>
<br>
For the specific case of two, your approach is about as simple as it can get. However, generalizing the code to handle 'r' at a time is pretty tricky. There's a library function for it in Python 2.6 and later, as mentioned by others, and the docs show a sample implementation.<br>
<br>
Clearly making a single function call is optimized in one sense. However, if you're looking for speed, chances are you could improve on your own function by changing the two loops. (tested in python 2.6)<br>
<br>
Consider:<div class="im"><br>
<br>
list1=['a','b','c','d','e']<br>
list2=[]<br>
<br></div>
for it1, val1 in enumerate(list1):<br>
for val2 in list1[it1+1:]:<br>
list2.append([val1, val2])<br>
<br>
print list2<br>
<br>
<br>
DaveA<div><div></div><div class="h5"><br>
<br>
<br>
<br>
<br>
<br>
<br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br>