Lists and Functions

Lists and Functions

Lists pass into and out of functions like any other value. Two details matter.

First, + joins two lists into a new one:

print([1, 2] + [3, 4])

Output:

[1, 2, 3, 4]

Second, a function that receives a list receives the list itself, not a copy. If the body changes it, the caller's list changes:

def add_signature(lines):
    lines.append("-- Ada")

message = ["Hello", "See you Friday"]
add_signature(message)
print(message)

Output:

['Hello', 'See you Friday', '-- Ada']

Sometimes that is exactly what you want. When it is not, build and return a new list instead of changing the parameter — slicing and + both produce new lists.

Exercise

  1. Define a function named swap_ends with one parameter, items (a list with at least two elements).
  2. It returns a new list with the first and last elements swapped and everything between them unchanged. Do not change items.

swap_ends([1, 2, 3, 4]) returns [4, 2, 3, 1].

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

Tests

import unittest


class TestSwapEnds(unittest.TestCase):
    def test_four_elements(self):
        self.assertEqual(swap_ends([1, 2, 3, 4]), [4, 2, 3, 1])

    def test_two_elements(self):
        self.assertEqual(swap_ends(["a", "b"]), ["b", "a"])

    def test_original_list_is_not_changed(self):
        items = [1, 2, 3]
        swap_ends(items)
        self.assertEqual(items, [1, 2, 3])
def swap_ends(items):
    return [items[-1]] + items[1:-1] + [items[0]]


print(swap_ends([1, 2, 3, 4]))
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.