1

I was solving a problem in python by using following code:

T = int(raw_input()) 
C=[] 
for x in range(T):     
    C[x]=int(raw_input()) 
res=[] 
for x in range(T):     
    res[x]=2**C[x]+2*C-1      
for x in range(T):     
    print "%d\n",(res[x])   

and this error came up:

Traceback (most recent call last):
  File "C:\Users\ACER\Documents\works\source code\python practice\Test1.py", line 4, in <module>
    C[x]=int(raw_input())
IndexError: list assignment index out of range

Can any solve this error pls

Samsquanch
  • 8,866
  • 12
  • 50
  • 89
crax
  • 546
  • 2
  • 9
  • 20
  • Your list is empty, so e.g. `C[0]` doesn't exist; you can't index beyond the end of a list. Try `C.append(int(raw_input))`. – jonrsharpe Aug 20 '14 at 14:28

2 Answers2

3

your list is empty. perl will expand array automatically but python won't.

C.append(int(raw_input()))

instead.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
0

You can't expand a Python list by assigning to an element past the end.

You need to expand the list explicitly but replacing

C[x]=int(raw_input()) 

with

C.append(int(raw_input()))

The same goes for res.

Last but not least, the 2*C in 2**C[x]+2*C-1 will give you a list. It's unclear what you're trying to do here, but 2*C isn't going to work. Did you mean 2*C[x]?

NPE
  • 486,780
  • 108
  • 951
  • 1,012