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?
I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using
array[i,j]
instead ofarray[i][j]
.For reference this is the piece of code where I had to use this :
Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.
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)
):Make it more reusable as a function.
I'm a bit surprised that the easiest way to create an initialised list is not in any of these answers. Just use a generator in the
list
function: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.This code generates an array that contains 10 random numbers.