Assigning a value to a Python list does not work?

The following code works correctly 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 using l[i] = raw_input("e"+str(i)+"=")instead?

Example: (does not 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 
+5
source share
4 answers

You can use indexing (for example obj[x]) to access or modify elements that already exist in list. For example, the following works because the positions in the list that we are referring to already exist:

>>> chars = ['a', 'b', 'c']
>>> chars[0]
'a'
>>> chars[0] = 'd'
>>> chars
['d', 'b', 'c']

However, accessing or changing elements in provisions that do not exist in 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 list comprehension )

N = int(raw_input("N="))
l = [raw_input("e" + str(i) + "=") for i in range(N)]
print l
+6

, , , , . , , .. - 0.

l = [0] * N

N 0.

:

l.append(raw_input("e"+str(i)+"="))
+4

, . i 0, l[0] .

+3

All Articles