The following code works properly for me:
# -*- coding: utf-8 -*-
N = int(raw_input("N="))
l=[]
i = 0
while i<N:
n = raw_input("e"+str(i)+"=")
l.append(n)
i = i+1
print l
But, why can't I simplify it by using l[i] = raw_input("e"+str(i)+"=")
instead?
Example: (doesn't work)
# -*- coding: utf-8 -*-
N = int(raw_input("N="))
l=[]
i = 0
while i<N:
l[i] = raw_input("e"+str(i)+"=")
i = i+1
print l
You can only use indexing (e.g. obj[x]
) to access or modify items that already exist in a list
. For example, the following works because the positions in the list that we are accessing already exist:
>>> chars = ['a', 'b', 'c']
>>> chars[0]
'a'
>>> chars[0] = 'd'
>>> chars
['d', 'b', 'c']
However, accessing or modifying items at positions that do not exist in a list
will not work:
>>> chars = ['a', 'b', 'c']
>>> chars[3]
...
IndexError: list index out of range
>>> chars[3] = 'd'
...
IndexError: list assignment index out of range
>>> chars
['a', 'b', 'c']
If you want to simplify your code, try: (it uses a list comprehension)
N = int(raw_input("N="))
l = [raw_input("e" + str(i) + "=") for i in range(N)]
print l
I think in your second example, I think you mean why you can't directly assign list elements. The answer to that is because the elements have not been initialized ie. the list size is still 0. You could do
l = [0] * N
To initialize the list to N elements with a value of 0.
Or you could just do:
l.append(raw_input("e"+str(i)+"="))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With