Practice: First and Last

Practice: First and Last

This exercise combines indexing, list building, and a conditional.

Exercise

  1. Define a function named bookends with one parameter, items (a list).
  2. It returns a new two-element list holding the first and last elements of items.
  3. If items is empty, return an empty list.

bookends([3, 7, 2, 9]) returns [3, 9]. bookends(["solo"]) returns ["solo", "solo"]. bookends([]) returns [].

Run your code to see the output, then press Submit.

Hints

  • Handle the empty case first and return early.
  • A one-element list still has a first and a last element — the same one.

Tests

import unittest


class TestBookends(unittest.TestCase):
    def test_four_numbers(self):
        self.assertEqual(bookends([3, 7, 2, 9]), [3, 9])

    def test_one_element_appears_twice(self):
        self.assertEqual(bookends(["solo"]), ["solo", "solo"])

    def test_empty_list_gives_empty_list(self):
        self.assertEqual(bookends([]), [])

    def test_two_elements(self):
        self.assertEqual(bookends(["a", "b"]), ["a", "b"])
def bookends(items):
    if len(items) == 0:
        return []
    return [items[0], items[-1]]


print(bookends([3, 7, 2, 9]))
print(bookends(["solo"]))
print(bookends([]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.