Lists as reference types in python
Question: Following is the piece of code that i wrote to calculate the nth prime number.
I initialize arr = [2,3,5]; and prime(arr,n) is supposed to modify arr to
contain first n prime numbers. But arr does not reflect changes after
prime(arr,n) is executed. I read that lists are passed as reference types ,so
what is the problem in the following code. t denotes the number of test cases
against which verification has to be done.

The program results in an error saying array index out of bound for arr.

    
    
    import sys;
    def prime (arr,n):
        while(len(arr)< n):
            num=arr[len(arr)-1]+1;prime=0;
            while(prime==0):
                prime = 1
                for val in arr:
                    if(num%val==0):
                        prime=0;
                        break;
                if(prime == 1):
                    print "hello";
                    arr = arr + [num];print arr; print "--";
                else:
                    num = num+1;
    
    
    t=raw_input();
    t=int(t);
    arr=[2,3,5];
    ans =[];
    for v in range (0,t):
        n = raw_input();
        n = int(n);
        if(n<=len(arr)):
            ans = ans + [arr[n-1]];
        else:
            prime(arr,n);print arr;print"arr was printed"
            ans= ans + [arr[n-1]];
    print ans;print 'ans ';
    

below is sample run of the above code

    
    
    >>> 
    1
    4
    hello
    [2, 3, 5, 7]
    --
    [2, 3, 5]
    arr was printed
    
    Traceback (most recent call last):
      File "C:\Users\Pulkit\Desktop\Random\nth_prime.py", line 30, in <module>
        ans= ans + [arr[n-1]];
    IndexError: list index out of range
    

Thanks in advance :)


Answer: Change the line:

    
    
    arr = arr + [num];
    

to

    
    
    arr.append(num)
    

The new line actually changes the `arr` array. The original line didn't change
it; it created a _new_ variable called `arr` (it was a [rebinding operation
instead of a mutating
one](http://en.wikipedia.org/wiki/Name_binding#Rebinding_and_mutation))

Sample run after this change:

    
    
    1
    4
    hello
    [2, 3, 5, 7]
    --
    [2, 3, 5, 7]
    arr was printed
    [7]
    ans 
    

