Tuples

Tuples

A tuple is a sequence like a list, but it cannot be changed after creation. It is written with parentheses:

point = (3, 7)
print(point[0])
print(len(point))

Output:

3
2

Indexing and slicing work as on lists. Assignment does not: point[0] = 5 raises TypeError.

A tuple can be unpacked into one variable per element:

x, y = point
print(x)
print(y)

Output:

3
7

The number of names on the left must match the number of elements.

Use a tuple for a fixed group of values that belong together — a coordinate, a date, a pair. Use a list when elements come and go.

Exercise

  1. Define a function named midpoint with two parameters, a and b — each a two-element tuple (x, y).
  2. It returns the point halfway between them, as a tuple: each coordinate is the average of the two inputs.

midpoint((0, 0), (4, 6)) returns (2.0, 3.0).

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

Tests

import unittest


class TestMidpoint(unittest.TestCase):
    def test_origin_to_4_6(self):
        self.assertEqual(midpoint((0, 0), (4, 6)), (2.0, 3.0))

    def test_same_point(self):
        self.assertEqual(midpoint((1, 1), (1, 1)), (1.0, 1.0))

    def test_negative_coordinates(self):
        self.assertEqual(midpoint((-2, 0), (2, 8)), (0.0, 4.0))

    def test_result_is_a_tuple(self):
        self.assertIsInstance(midpoint((0, 0), (2, 2)), tuple)
def midpoint(a, b):
    ax, ay = a
    bx, by = b
    return ((ax + bx) / 2, (ay + by) / 2)


print(midpoint((0, 0), (4, 6)))
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.