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?
Best Answer
You cannot assign to a list like
lst[i] = something
, unless the list already is initialized with at leasti+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:
Assigning a value to an existing element of the above list:
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]
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)
):