Having Trouble Making a List of Lists of a Designated Size

Create an empty list with certain size in Python

You cannot assign to a list like xs[i] = value, unless the list already is initialized with at least i+1 elements. Instead, use xs.append(value) to add elements to the end of the list. (Though you could use the assignment notation if you were using a dictionary instead of a list.)

Creating an empty list:

>>> xs = [None] * 10
>>> xs
[None, None, None, None, None, None, None, None, None, None]

Assigning a value to an existing element of the above list:

>>> xs[1] = 5
>>> xs
[None, 5, None, None, None, None, None, None, None, None]

Keep in mind that something like xs[15] = 5 would still fail, as our list has only 10 elements.

range(x) creates a list from [0, 1, 2, ... x-1]

# 2.X only. Use list(range(10)) in 3.X.
>>> xs = range(10)
>>> xs
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

>>> def display():
... xs = []
... for i in range(9): # This is just to tell you how to create a list.
... xs.append(i)
... return xs
...
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

How to create a fix size list in python?

(tl;dr: The exact answer to your question is numpy.empty or numpy.empty_like, but you likely don't care and can get away with using myList = [None]*10000.)

Simple methods

You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:

>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]

(Here _ is just a variable name, you could have used i.)

You can also do so like this:

>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]

You probably don't need to optimize this. You can also append to the array every time you need to:

>>> x = []
>>> for i in range(10):
>>> x.append(i)

Performance comparison of simple methods

Which is best?

>>> def initAndWrite_test():
... x = [None]*10000
... for i in range(10000):
... x[i] = i
...
>>> def initAndWrite2_test():
... x = [None for _ in range(10000)]
... for i in range(10000):
... x[i] = i
...
>>> def appendWrite_test():
... x = []
... for i in range(10000):
... x.append(i)

Results in python2.7:

>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
... print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
...
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop

Results in python 3.2:

initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop

As we can see, it is likely better to do the idiom [None]*10000 in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.


Uninitialized memory

These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.

This is not an asymptotic speedup (because it's O(N)), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000).

If you want something similar in python, you can use the numpy numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty or numpy.empty_like

That is the real answer to your question.

How to create a number of empty nested lists in python

Try a list comprehension:

lst = [[] for _ in xrange(a)]

See below:

>>> a = 3
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], []]
>>> a = 10
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], [], [], [], [], [], [], [], []]
>>> # This is to prove that each of the lists in lst is unique
>>> lst[0].append(1)
>>> lst
[[1], [], [], [], [], [], [], [], [], []]
>>>

Note however that the above is for Python 2.x. On Python 3.x., since xrange was removed, you will want this:

lst = [[] for _ in range(a)]

Create sub-lists in lists in Python

pop = [[]]*popLen should work, but it is likely not what you want since it creates a list filled with the same nested list popLen times, meaning that a change to one of the list elements would appear in the others:

>>> a = [[]] * 3
>>> a[0].append(42)
>>> a
[[42], [42], [42]]

A better alternative would be

pop = [[] for _ in range(popLen)]  # use xrange() in Python 2.x

which eliminates this issue:

>>> a = [[] for _ in range(3)]
>>> a[0].append(42)
>>> a
[[42], [], []]

How to make a new List in Java

List myList = new ArrayList();

or with generics (Java 7 or later)

List<MyType> myList = new ArrayList<>();

or with generics (Old java versions)

List<MyType> myList = new ArrayList<MyType>();


Related Topics



Leave a reply



Submit