Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list or tuple of empty lists in Python?

I need to incrementally fill a list or a tuple of lists. Something that looks like this:

result = [] firstTime = True for i in range(x):     for j in someListOfElements:         if firstTime:             result.append([f(j)])         else:             result[i].append(j) 

In order to make it less verbose an more elegant, I thought I will preallocate a list of empty lists

result = createListOfEmptyLists(x) for i in range(x):     for j in someListOfElements:         result[i].append(j) 

The preallocation part isn't obvious to me. When I do result = [[]] * x, I receive a list of x references to the same list, so that the output of the following

result[0].append(10) print result 

is:

[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]] 

I can use a loop (result = [[] for i in range(x)]), but I wonder whether a "loopless" solution exists.

Is the only way to get what I'm looking for

like image 611
Boris Gorelik Avatar asked Oct 07 '10 08:10

Boris Gorelik


People also ask

How do you create an empty list of tuples in Python?

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

How would you create an empty list of tuples?

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

Can you create a tuple of lists in Python?

We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.


1 Answers

result = [list(someListOfElements) for _ in xrange(x)] 

This will make x distinct lists, each with a copy of someListOfElements list (each item in that list is by reference, but the list its in is a copy).

If it makes more sense, consider using copy.deepcopy(someListOfElements)

Generators and list comprehensions and things are considered quite pythonic.

like image 153
Will Avatar answered Sep 18 '22 05:09

Will