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

when i do this , and give an input suppose 1011 , it says list indexing error- " 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?

asked Apr 9, 2010 at 9:32
2
  • 2
    This code should work, the problem is probably elsewhere... Commented Apr 9, 2010 at 9:35
  • 1
    Can you post a full example that demonstrates the problem reproducibly? Commented Apr 9, 2010 at 9:40

2 Answers 2

4

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.

answered Apr 9, 2010 at 9:52
3

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()
answered Apr 9, 2010 at 9:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.