Feed on
Posts
Comments

let’s say you’ve got a list of the numbers 0 through 4 and you wanted all 32 possible combinations of them.  to get that list:

list_of_five = range(0,5)   

swap_list_list = [[]]

for swap in list_of_five:

    temp_lists = []

    for list_stub in swap_list_list:

        this_list = copy.copy(list_stub)

        this_list.append(swap)

        temp_lists.append(this_list)

temp_lists.append(list_stub)

    swap_list_list = temp_lists

print swap_list_list

 

 


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

6 Responses to “get all possible combinations of a list’s elements in python”

  1. on 21 Dec 2008 at 12:31 am shady

    After doing “import copy” to your code, I get this output.

    $ python combo.py
    [[4], []]

  2. […] found some code (by googling) that apparently does what I’m looking for, but I found the code fairly opaque […]

  3. on 17 Mar 2015 at 3:00 am P.K. Subramanian

    Yes. You got this wrong.

    When you don’t have import copy module this is completely useless.

  4. […] found some code (by googling) that apparently does what I’m looking for, but I found the code fairly opaque […]

  5. […] 코드를 찾았 습니다 찾고있는 것을 분명히하는 (구글링에 의해)를 찾았지만 코드가 상당히 불투명하고 사용하는 것에주의를 기울였습니다. 또한 더 ìš°ì•„í•œ 솔루션이 있어야한다고 생각합니다. […]

  6. on 22 Sep 2023 at 4:24 pm clean energy

    I savour, cause I found exactly what I used to be looking for.
    You’ve ended my four day long hunt! God Bless you man. Have
    a great day. Bye

Did I get this wrong? Let me know!

Trackback URI | Comments RSS