Given the following assignment of a variable: LS = [1, 9, 2, 8, 3, 7, 5, 4]…

2023

Given the following assignment of a variable: LS = [1, 9, 2, 8, 3, 7, 5, 4] print(LS[::-2] + LS[::-2]) What will be the output of the following?

Answer: C. [4, 7, 8, 9, 4, 7, 8, 9]Concept: In Python, slice syntax seq[start:stop:step] with a negative step walks the sequence from back to front. When start and stop are omitted and step is…

  1. A.

    [5, 3, 2, 1, 9, 8, 7, 4]

  2. B.

    [1, 2, 3, 5, 4, 7, 8, 9]

  3. C.

    [4, 7, 8, 9, 4, 7, 8, 9]

  4. D.

    [9, 8, 7, 4, 5, 3, 2, 1]

Attempted by 2037 students.

Show answer & explanation

Correct answer: C

Concept: In Python, slice syntax seq[start:stop:step] with a negative step walks the sequence from back to front. When start and stop are omitted and step is negative, slicing begins at the LAST element (index -1) and moves backward by the absolute value of step each time, stopping once it would go past the front of the sequence — it is always a single continuous pass across the WHOLE sequence, never two separate parity groups treated independently.

  1. Index the list: LS = [1, 9, 2, 8, 3, 7, 5, 4] sits at indices 0 through 7 respectively.

  2. LS[::-2] omits start and stop, so the walk begins at the last index (7) and steps backward by 2 each time, visiting indices 7, 5, 3, 1.

  3. Reading off the values at those indices: LS[7] = 4, LS[5] = 7, LS[3] = 8, LS[1] = 9, so LS[::-2] = [4, 7, 8, 9].

  4. Concatenating the slice with itself: [4, 7, 8, 9] + [4, 7, 8, 9] = [4, 7, 8, 9, 4, 7, 8, 9].

Cross-check: reversing the entire list gives [4, 5, 7, 3, 8, 2, 9, 1]; taking every element at positions 0, 2, 4, 6 of that reversal (equivalent to a positive step of 2 applied after the reversal) gives the same four values 4, 7, 8, 9, confirming the slice by an independent route.

Final output: [4, 7, 8, 9, 4, 7, 8, 9]

Explore the full course: Rssb Senior Computer Instructor

Loading lesson…