Home > OS >  python - why this output of list?
python - why this output of list?

Time:06-05

I want to understand what A[A[i]] means in this code:

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

for i in range(len(A)-1):
    A[i] = A[i 1]

A[len(A)-1] = temp

for i in range (len(A)):
    print(A[A[i]], end ="" )

output :

10432
Process finished with exit code 0

I know the output but I need to understand how did we get it, specially this part:

print(A[A[i]], end ="" )

what does A[A[i]] mean?

CodePudding user response:

A[A[i]] is just the element of A with index A[i]. For example, if you have A = [1, 2], A[A[i]] = 2 if i = 0 because A[0] = 1 so A[A[0]] = A[1] = 2.

And for your information, end="" just means that python won't skip a line after printing the value.

CodePudding user response:

All the elements of: A = [1,4,2,0,3] are also, by coincidence valid indexes into A.

Note that the list A has 5 elements and each element is in the range 0..4.

This means that for any A[i] where i is a valid index retrieves one of the values, which itself is a valid index.

So, looking at the last two lines:

for i in range (len(A)):
    print(A[A[i]], end ="" )

we can see that the for loop causes i to be a valid index each time round, therefore A[i] is a valid index, therefore A[A[i]] returns one of the values from A.

CodePudding user response:

After Evaluating the following piece of code:

A=[1,4,2,0,3]
temp = A[0]
for i in range(len(A)-1):
    A[i] = A[i 1]
A[len(A)-1] = temp

we get the updated array: A=[4,2,0,3,1] Now the remaining piece of code can be evaluated as:

  1. for i=0 we have A[A[0]]=A[4]=1;
  2. for i=1 we have A[A[1]]=A[2]=0;
  3. for i=2 we have A[A[2]]=A[0]=4;
  4. for i=3 we have A[A[3]]=A[3]=3;
  5. for i=4 we have A[A[4]]=A[1]=2;

As format is given as => end="" the result is printed as : 10432

  • Related