user155876
user155876

Reputation: 361

Creating a tuple with n entries for n lists

If I have a function that creates a random number of lists and I want the final result to return a tuple containing those lists - is it at all possible to do this?

Since tuples are immutable and the number of elements in a tuple cannot be changed once it has been created, then how can one be automatically generated which contains n entries for n lists?

Unlike lists, expanding the entries of a tuple can't simply be changed with a command like .append().

EDIT: It just dawned on me that I could create a tuple with a really large number of entries e.g. tuple = (a,b,c,d,e,f,g,h, ... to infinity) to cover n lists and then pass on the values of the tuple, which contain a list, to a new tuple with the exact number of n entries but this seems like a really inefficient method.

Upvotes: 0

Views: 1301

Answers (1)

gtlambert
gtlambert

Reputation: 11961

Create a list of lists, then pass that list to the built in tuple() function:

my_lists = [[1, 2], [5, 7], [8, 9]]
my_tuple = tuple(my_lists)
print(my_tuple)

Output

([1, 2], [5, 7], [8, 9])

Upvotes: 1

Related Questions