How do I create an empty list that can hold 10 elements?
After that, I want to assign values in that list. For example:
xs = list()
for i in range(0, 9):
xs[i] = i
However, that gives IndexError: list assignment index out of range. Why?
Editor’s note:
In Python, lists do not have a set capacity, but it is not possible to assign to elements that aren’t already present. Answers here show code that creates a list with 10 "dummy" elements to replace later. However, most beginners encountering this problem really just want to build a list by adding elements to it. That should be done using the .append method, although there will often be problem-specific ways to create the list more directly. Please see Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list? for details.
You cannot assign to a list like
xs[i] = value, unless the list already is initialized with at leasti+1elements (because the first index is 0). Instead, usexs.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:
Assigning a value to an existing element of the above list:
Keep in mind that something like
xs[15] = 5would still fail, as our list has only 10 elements.range(x) creates a list from [0, 1, 2, … x-1]
Using a function to create a list:
List comprehension (Using the squares because for range you don’t need to do all this, you can just return
range(0,9)):