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.
swap_ends with one parameter, items (a list with at least two elements).items.swap_ends([1, 2, 3, 4]) returns [4, 2, 3, 1].
Run your code to see the output, then press Submit.
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]))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.