I have a list of lists (generated with a simple list comprehension):
>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
>>> base_lists
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]]
I want to turn this entire list into a tuple containing all of the values in the lists, i.e.:
resulting_tuple = (1,1,1,2,1,3,1,4,1,5,2,1,2,2,2,3,2,4,2,5)
What would the most effective way to do this be? (A way to generate this same tuple with list comprehension would also be an acceptable answer.) I’ve looked at answers here and in the Python documentation, however I have been unable to find a suitable one.
EDIT:
Many thanks to all who answered!
Edit: note that, with
base_listsso short, the genexp (with unlimited memory available) is slow. Consider the following filetu.py:Now:
When lists are longer (i.e., when performance really matters) things are a bit different. E.g., putting a
100 *on the RHS definingbase_lists:so for long lists only
withsumis a performance disaster — the others are in the same ballpark, although clearlyitertoolshas the edge, and list comprehensions (when abundant memory is available, as it always will be in microbenchmarks;-) are faster than genexps.Using
1000 *, genexp slows down by about 10 times (wrt the100 *), withit and listcomp by about 12 times, and withsum by about 180 times (withsum isO(N squared), plus it’s starting to suffer from serious heap fragmentation at that size).