Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising an n-length tuple of lists

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).

like image 233
Patrick Avatar asked May 15 '16 04:05

Patrick


People also ask

How do you initialize a list of tuples in Python?

Initialize a TupleYou can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.

Can Len () be used in tuples?

Python tuple method len() returns the number of elements in the tuple.

How do you assign a tuple of length 1?

How to assign a tuple of length 1 to a? A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.


2 Answers

Use a genex instead of a LC.

tuple([] for _ in range(list_length))
like image 184
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 15:09

Ignacio Vazquez-Abrams


Try this:

tuple = (elements,) * list_length
like image 34
Piyush Agrawal Avatar answered Sep 17 '22 15:09

Piyush Agrawal