0

I have a list, to make it easier to understand it's structure I'll write it out like so:

mylist = [[["a","b","c","d"]...]...]

Where the ... means the previous list is repeated (although the values inside may change)

An example list would be:

mylist = [[["a","b","c","d"], ["e","f","g","h"]], [["i", "j", "k", "l"]], [["m","n","o","p"], ["q","r","s","t"]]]

My current method is:

mylist2 = []
for a in mylist[0]:
    for b in mylist[1]:
        for c in mylist[2]:
            mylist2.append([a,b,c])

However this is very long, especially since in my actual code it goes on up to for x in mylist[35]

Is there a better way for me to write this code?

6
  • 1
    .. this is very long.. - did you mean it takes a long time to execute? Will you be using mylist2 more than once? Commented Oct 17, 2019 at 22:31
  • @wwii I mean the code is very long. There are nested for loops in for loops in for loops... Around 35 times. That's 35 tabs before code! Surely there's a shorter and faster way to do this Commented Oct 17, 2019 at 22:35
  • And the variable mylist2 is returned from the function as soon as it is found Commented Oct 17, 2019 at 22:36
  • Did you look through the Python docs for something that might work for you? Commented Oct 17, 2019 at 22:39
  • 1
    Something in docs.python.org/3/library/itertools.html Commented Oct 17, 2019 at 22:49

1 Answer 1

3

your code

%%timeit
mylist2 = []
for a in mylist[0]:
    for b in mylist[1]:
        for c in mylist[2]:
            mylist2.append([a,b,c])
# 809 ns ± 18.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

use itertools

import itertools
%%timeit
list(itertools.product(*mylist))
# 528 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Sign up to request clarification or add additional context in comments.

2 Comments

Minor difference in behavior: The latter makes a list of three-tuples, where the former is making three-lists. If mutability is required, the latter can be efficiently made to match the former by mapping to list: list(map(list, itertools.product(*mylist))). But yes, this is the obvious way to go here, and especially useful when mylist might have a variable number of sub-lists.
@ShadowRanger Thank you for your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.