Unpack and Swap

Easy ⏱ 8 min 82% acceptance ★★★★★ 4.6
Write a function swap_first_last(items) that takes a list items and returns a new list with the first and last elements swapped, using Python's multiple-assignment/unpacking syntax (no manual temp-variable juggling of indices).

Examples

Example 1
Input
swap_first_last([1, 2, 3, 4])
Output
[4, 2, 3, 1]
Explanation

First (1) and last (4) traded places.

Example 2
Input
swap_first_last([7])
Output
[7]
Explanation

Single element: swapping with itself changes nothing.

Constraints

  • `items` has at least one element.
  • Do not mutate the input list; return a new one.

Topics

Variables & Data Typesmultiple assignment

Companies

AmazonRazorpay

Hints

Hint 1

Copy the list first, e.g. with items[:] or list(items).

Hint 2

result[0], result[-1] = result[-1], result[0] does a tuple-unpack swap.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.