0

I want to create a global array so that these functions fib() and shoot() can share it. Here is my code:

global f
f=[0]*1000
def fib(n):

    f[0]=1  ## error here  
    f[1]=1
    for i in xrange(2,n+1):
        f[i]=f[i-1]+f[i-2]

def shoot(aliens):
    ...
    place to use f[] here

fib(999)
print shoot(line)

however it shows an error.

Traceback (most recent call last):
File  line 56, in <module>
fib(999)
line 42, in fib
f[0]=1
TypeError: 'file' object does not support item assignment

please help!

Edit: Comments below made me realise that I had "with open('somefile') as f" in another part of my code not shown here. I removed that, and now, it's working.

4
  • 2
    "line 42, in fib" Is there more you're not showing us? Commented Jul 19, 2013 at 8:52
  • 8
    You already have a variable called f which is a file. Commented Jul 19, 2013 at 8:52
  • @Haidro that's all It has. I Just copied it directly to here. Commented Jul 19, 2013 at 8:59
  • @TungPham I highly doubt it. You probably overrode your list f Commented Jul 19, 2013 at 9:00

3 Answers 3

2

You overrode your list f with:

with open(...) as f:

You can either:

  • Rename the list

  • Change the name of the file (i.e, something like as myfile)

Because this happened, you're then trying to access the list with indexing, but you're actually working with a file object. This is why you get a TypeError: 'file' object does not support item assignment

Sign up to request clarification or add additional context in comments.

Comments

0

Just move the line global f into your functions:

f=[0]*1000
def fib(n):
    global f

    f[0]=1  ## error here  
    f[1]=1
    for i in xrange(2,n+1):
        f[i]=f[i-1]+f[i-2]

def shoot(aliens):
    ...
    global f
    ... do stuff with f here ...

Or alternatively, pass f in as a parameter to the functions:

def fib(n, f):
    ...

def shoot(aliens, f):
    ...

4 Comments

Okay, but this doesn't explain the error. Infact, his current code should work fine
@haidro oh yeah - you're right! I didn't look at that. Do you think there is a with open('somefile') as f somewhere higher in the program?
@TungPham what happens if you rename your array to something else, like: array_f? Does this fix your problem?
@NickBurns OH. you're right. I have "with open('somefile') as f" in my code. now, it's working. Thank you.
0

You can simply declare the array in the beginning.

Whenever you wish to modify/access/change your arraym just use the keyword global to refer to that array.

Here is an example:

myarray=[]

def func():
     global myarray
     myarray[0]=1

Cheers!

Comments

Your Answer

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.