Kaimbridge
Kaimbridge

Reputation: 1

Basic Variable Indexing

How do you do a simple index/array in Python? For example, in a traditional BASIC language, all you would have to do is something like

10 Dim V(5)
20 For N = 1 to 5:V(N)=2^N+1/N:? N,V(N):Next

which would output:

1  3.0
2  4.5
3  8.33333333333
4  16.25
5  32.2

If I wanted the weights of Gaussian quadrature, I could do:

UL=5
[x,w] = p_roots(UL)
for N in range(UL):
     print N,w[N]

which works:

1  0.236926885056
2  0.478628670499
3  0.568888888889
4  0.478628670499
5  0.236926885056

but if I try my BASIC, as it would seem to be

UL=5
for N in range(1,UL+1):
    V[N]=2**N+1.0/N
    print N,V[N]

which rejects it as

    V[N]=2**N+1.0/N
NameError: name 'V' is not defined

and if I try to mimic the Gaussian example

UL=5
[V]=2**UL+1.0/UL
for N in range(1,UL+1):
    print N,V[N]

I get

    [V]=2**UL+1.0/UL
TypeError: 'float' object is not iterable

In terms of arrays/indexing, isn't V[N] the same as w[N] (which works in its example)? All of the Python documentation seems to jump into more complicated cases, without providing more rudimentary examples like the above.

Upvotes: 0

Views: 210

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

Your errors seem clear: in your first you have not defined V at all (compare with your BASIC version where you used Dim V) and in your second you have assigned V to a single value (2**UL+1.0/UL), not a list of values.

However, you should note that Python lists are not arrays, and you do not size them. Instead, you compose them as you go by appending. For instance, in the first version:

UL = 5
V = []
for N in range(1,UL+1):
    V.append(2**N+1.0/N)

Upvotes: 1

Related Questions