Create an empty list in python with certain size

Posted on

Question :

Create an empty list in python with certain size

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed to display 0 to 9:

s1 = list();
for i in range(0,9):
   s1[i] = i

print  s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

Can someone explain why?

Answer #1:

You cannot assign to a list like lst[i] = something, unless the list already is initialized with at least i+1 elements. You need to use append to add elements to the end of the list. lst.append(something).

(You could use the assignment notation if you were using a dictionary).

Creating an empty list:

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

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

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

Keep in mind that something like l[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.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
>>> 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]
Answered By: varunl

Answer #2:

Try this instead:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

lst = [None] * 10
for i in range(10):
    lst[i] = i

Admittedly, that’s not the Pythonic way to do things. Better do this:

lst = []
for i in range(10):

Or even simpler, in Python 2.x you can do this to initialize a list with values from 0 to 9:

lst = range(10)

And in Python 3.x:

lst = list(range(10))
Answered By: Óscar López

Answer #3:

varunl’s currently accepted answer

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

Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

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

As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects

>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]

There is likely a default, built-in python way of doing this (instead of writing a function), but I’m not sure what it is. Would be happy to be corrected!

Edit: It’s [ [] for _ in range(10)]

Example :

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]
Answered By: James L.

Answer #4:

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

Answered By: Mohammed Hossain

Answer #5:

There are two “quick” methods:

x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]

It appears that [None]*x is faster:

>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
>>> timeit("[None for _ in xrange(100)]",number=10000)

But if you are ok with a range (e.g. [0,1,2,3,...,x-1]), then range(x) might be fastest:

>>> timeit("range(100)",number=10000)
Answered By: mgoldwasser

Answer #6:

I’m surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

x = [[] for i in range(10)]
Answered By: Bow

Answer #7:

The accepted answer has some gotchas. For example:

>>> a = [{}] * 3
>>> a
[{}, {}, {}]
>>> a[0]['hello'] = 5
>>> a
[{'hello': 5}, {'hello': 5}, {'hello': 5}]

So each dictionary refers to the same object. Same holds true if you initialize with arrays or objects.

You could do this instead:

>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]
Answered By: user2233706

Answer #8:

(This was written based on the original version of the question.)

I want to create a empty list (or whatever is the best way) can hold 10 elements.

All lists can hold as many elements as you like, subject only to the limit of available memory. The only “size” of a list that matters is the number of elements currently in it.

but when I run it, the result is []

print display s1 is not valid syntax; based on your description of what you’re seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

Calling display does not modify the list you pass in, as written. Your code says “s1 is a name for whatever thing was passed in to the function; ok, now the first thing we’ll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we’ll modify that list“. This has no effect on the value you passed in.

There is no reason to pass in a value here. (There is no real reason to create a function, either, but that’s beside the point.) You want to “create” something, so that is the output of your function. No information is required to create the thing you describe, so don’t pass any information in. To get information out, return it.

That would give you something like:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you’re starting from 0.) So then you end up with

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

However, this is still missing the mark; range is not some magical keyword that’s part of the language the way for and def are, but instead it’s a function. And guess what that function returns? That’s right – a list of those integers. So the entire function collapses to

def create_list():
    return range(10)

and now you see why we don’t need to write a function ourselves at all; range is already the function we’re looking for. Although, again, there is no need or reason to “pre-size” the list.

Answered By: Karl Knechtel

Leave a Reply

Your email address will not be published. Required fields are marked *