开发者

assigning a list in python

pt=[2]
pt[0]=raw_input()

when i do this , and give an input suppose 1011 , it says list indexing error- "开发者_JAVA技巧 list assignment index out of range" . may i know why? i think i am not able to assign a list properly . how to assign an array of 2 elements in python then?


Try this:

pt = list()
pt.append(raw_input())
pt.append(raw_input())
print pt

You now have two elements in your list. Once you are more familiar with python syntax, you might write this as:

pt = [raw_input(), raw_input()]

Also, note that lists are not to be confused with arrays in Java or C: Lists grow dynamically. You don't have to declare the size when you create a new list.

BTW: I tried out your example in the interactive shell. It works, but probably not as you expected:

>>> pt = [2]
>>> pt[0] = raw_input()
1011
>>> pt
['1011']

I'm guessing you thought pt = [2] would create a list of length 2, so a pt[1] = raw_input() would fail like you mentioned:

>>> pt = [2]
>>> pt[0] = raw_input()
1011
>>> pt[1] = raw_input() # this is an assignment to an index not yet created.
1012
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Actually, pt = [2] creates a list with one element, having the value 2 at index 0:

>>> pt = [2]
>>> pt
[2]
>>>

So you can assign to the index 0 as demonstrated above, but assigning to index 1 will not work - use append for appending to a list.


It's not clear what you are trying to do. My guess is that you are trying to do this:

pt = [2] # Create array with two elements?
for i in range(2):
    pt[i] = raw_input()

Note that the first line does not create an array with two elements, it creates a list with one element: the number 2. You could try this instead, although there are more Pythonic ways to do it:

pt = [None] * 2
for i in range(2):
    pt[i] = raw_input()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜