Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a value to Python list doesn't work?

Tags:

python

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 
like image 682
kn3l Avatar asked Apr 04 '11 20:04

kn3l


2 Answers

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
like image 115
bradley.ayers Avatar answered Sep 21 '22 12:09

bradley.ayers


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)+"="))
like image 29
GWW Avatar answered Sep 22 '22 12:09

GWW