2

I am trying to figure out how to solve this question. I know the answer, but I cannot figure out why it's correct.

primes = [2, 3, 5, 7, 11]

What does it contain after executing the following loop?

for i in range(2):
     primes[4 - i] = primes[i]

answer: 2, 3, 5, 3, 2

I'm stuck in primes[4 - i]... part. Can somebody please explain this part? I know it is the index position.

0

4 Answers 4

2

range(n) gives you a sequence of numbers from 0 to n - 1.

If you replace the range function by its sequence in your code you basically get this:

for i in [0, 1]:
     primes[4 - i] = primes[i]

Each time you loop, i will start from 0 and get bigger and bigger. Which in turn means that 4 - i will start from 4 and get smaller.

1st loop: 4 -i = 4 - 0 = 4

2nd loop: 4 - i = 4 - 1 = 3

(and so on if your value in range was bigger than 2)

The line primes[4 - i] = primes[i] means that you're assigning to the index 4 - i the value stored at the index i.

In your example, your loop is actually doing this:

1st loop: primes[4] = primes[0]

2nd loop: primes[3] = primes[1]

Giving you the result you currently have.

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

Comments

1

This code starts by reversing the array, but it overwrites the end of the array so overall it just outputs a palindrome.

Comments

0

The code is just swapping the last with first,second last with second and so on. until the loop is over

Comments

-1

The array is build with indices:

0,1,2,...,n

You can enter each index by selecting its position e.g. array[2] gets you the third value of the array.

Your code, like @script8man explained, selects the 4-ith index. in a range(2) (0,1), it will return the 4th and 3rd index, this index is overwritten with the i-th index (0,1).

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.