Creating Lists

Creating Lists

A list holds several values in order. It is written with square brackets, values separated by commas:

colors = ["red", "green", "blue"]
numbers = [4, 8, 15]

Each value in a list is an element. Elements are read by position with square brackets. The position is called the index, and counting starts at 0:

colors = ["red", "green", "blue"]
print(colors[0])
print(colors[2])

Output:

red
blue

Negative indexes count from the end: -1 is the last element, -2 the second to last:

print(colors[-1])

Output:

blue

Reading an index that does not exist is an error: for a three-element list, colors[3] raises IndexError.

Exercise

The starter code creates a list queue with five names.

  1. Create first — the first element, by index.
  2. Create third — the third element.
  3. Create last — the last element, using a negative index.
  4. Print all three.

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

Tests

import unittest


class TestCreatingLists(unittest.TestCase):
    def test_first_is_ada(self):
        self.assertEqual(first, "Ada")

    def test_third_is_alan(self):
        self.assertEqual(third, "Alan")

    def test_last_is_barbara(self):
        self.assertEqual(last, "Barbara")

    def test_queue_is_unchanged(self):
        self.assertEqual(queue, ["Ada", "Grace", "Alan", "Edsger", "Barbara"])
queue = ["Ada", "Grace", "Alan", "Edsger", "Barbara"]

first = queue[0]
third = queue[2]
last = queue[-1]

print(first)
print(third)
print(last)
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.