Initialising an n-length tuple of lists
Asked Answered
D

2

16

Is there a more efficient, simpler way to create a tuple of lists of length 'n'?

So in Python, if I wanted to create a list of lists I could do something like:

[[] for _ in range(list_length)]

And to create a tuple of lists of a similar nature I could technically write:

tuple([[] for _ in range(list_length)])

But is this computationally inefficient, could it be written in a nicer way?

Warning: For anyone else who thought it was good idea to put mutable objects such as lists inside a tuple (immutable); it actually appears to be generally faster (computationally) to just use a list (in my case a list of lists).

Devisable answered 15/5, 2016 at 4:49 Comment(2)
A tuple of lists is an unusual thing to want, outside of some short-term, narrow-scoped uses like function star-arguments. The primary advantage of a tuple is that it's immutable, for use in sets, as dictionary keys, etc. But if a tuple's contents are mutable, the tuple itself can't be used safely in any of those roles.Enidenigma
Wow, in fact (according to my very sloppy benchmark) it takes ever so slightly longer to create, access and append to the lists in the tuple when compared to doing the same thing with a list of lists.Devisable
K
19

Use a genex instead of a LC.

tuple([] for _ in range(list_length))
Karen answered 15/5, 2016 at 4:56 Comment(2)
Thanks! For some reason that didn't occur to me.Devisable
(genex stands for generator expression, LC stands for list comprehension)Touchline
R
11

Try this:

tuple = (elements,) * list_length
Reconcilable answered 12/3, 2020 at 21:45 Comment(2)
It's bad to name your variables the same as built-in data types or functions.Fatling
Note that ([],)*3 will create ([],[],[]). However, the lists within the tuple are not independent and changes on any of them will reflect on all of them.Rojo

© 2022 - 2024 — McMap. All rights reserved.