Farid A
Farid A

Reputation: 325

how does bracket operator work in python?

I was reviewing a code written in python, part of it looks like this.

n = len(A)
T = n * [False]
for i in xrange(n + 1):
    T[A[i]] = True

which A is an array of integer values. I assume the second line creates a list of size n with values of false, but it is not clear to me how T[A[i]] works. Does it access the element of T at A[i]? But A[i] is not necessarily between 0 and n.

Upvotes: 2

Views: 1254

Answers (3)

Aks
Aks

Reputation: 1232

See farid,

You are confused about T[A[i]]. Let me expalin you...

A and T both are arrays.

for T[A[i]]=True, A[i] is an index for array T.

Because length of T is n only. SO if array A having all integers values < n(lenght of ARRAY T). The code will work fine.

But if not: Python will through index out of range exception

Upvotes: 0

justhalf
justhalf

Reputation: 9107

It's indeed accessing element of T at A[i]. And it's indeed true that A[i] might not be between 0 and n. But that's what the code does.

So if you are expecting that T[A[i]] should work, probably there are some code before, that ensures A[i] always between 0 and n.

Upvotes: 2

aIKid
aIKid

Reputation: 28292

A[i] is probably a number, and yes, if its length is >n, you'll get an IndexError.

The actual variable passed is something like:

T[number]

Here is a little example, we have the A variable:

>>> A = [4, 3, 2, 1, 0]

And we have the T variable as:

>>> T = ['A', 'B', 'C', 'D', 'E']

And then we do the loop:

>>> for i in range(5):
    print T[A[i]]

Result:

E
D
C
B
A

As long as A[i] is not higher than n, it'll be fine. Hope this helps!

Upvotes: 1

Related Questions