What will be the output of the following Python code? a = (1,2,3,4,5)…

2024

What will be the output of the following Python code?

a = (1,2,3,4,5)

print(a[-4:-1])

Answer: A. (2, 3, 4)ConceptA Python slice seq[start:stop] returns the items from index start up to but NOT including index stop — the stop index is exclusive. A negative index…

  1. A.

    (2, 3, 4)

  2. B.

    (3, 4, 5)

  3. C.

    (2, 3, 4, 5)

  4. D.

    (1, 2, 3)

  5. E.

    (3, 4)

Attempted by 82 students.

Show answer & explanation

Correct answer: A

Concept

A Python slice seq[start:stop] returns the items from index start up to but NOT including index stop — the stop index is exclusive. A negative index counts from the end, where -1 is the last element, -2 the second-last, and so on.

Application

For the tuple a = (1, 2, 3, 4, 5), map each negative index to its element:

Negative index

Element

-5

1

-4

2

-3

3

-2

4

-1

5

  1. The slice a[-4:-1] starts at index -4, which is the element 2.

  2. It collects elements while moving forward toward the stop index -1, covering indices -4, -3 and -2.

  3. It stops BEFORE index -1, so the element at -1 (the value 5) is excluded.

  4. The collected elements are those at -4, -3, -2, i.e. 2, 3 and 4.

Therefore print(a[-4:-1]) outputs the tuple (2, 3, 4).

Cross-check

The same slice can be read with the equivalent positive indices. For this 5-element tuple, -4 corresponds to index 1 and -1 corresponds to index 4, so a[-4:-1] is the same as a[1:4]. A positive-index slice a[1:4] also takes indices 1, 2 and 3 while excluding index 4, giving the same result. Both readings agree.

Explore the full course: Ibps So It Mains

Loading lesson…