easy +10 pts

Image channel swap

Rotate RGB channels of an image represented as a nested list.

Given an image represented as a 3D list of shape (height, width, 3) where each pixel is a list [R, G, B] with integer values 0-255, write a function `swap_channels(image)` that returns a new image with the red and blue channels swapped. The original image must remain unchanged. The result should be a new 3D list with the same shape. Each pixel in the output should be [B, G, R] in that order.

Constraints

The input image is a non-empty nested list. Height and width are at least 1. All channel values are integers between 0 and 255. The function should not modify the input image. Output should be a new list (not a view or reference). Complexity: O(height * width) time, O(height * width) space.

Example

>>> image = [
...     [[255, 0, 0], [0, 255, 0]],
...     [[0, 0, 255], [128, 64, 32]]
... ]
>>> swap_channels(image)
[[[0, 0, 255], [0, 255, 0]], [[255, 0, 0], [32, 64, 128]]]
>>> # original unchanged
>>> image[0][0]
[255, 0, 0]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a nested list comprehension to build the new image.
Remember to create new pixel lists, not reuse the same list object.
The output pixel is [pixel[2], pixel[1], pixel[0]].
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.