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.
The starter code creates a list queue with five names.
first — the first element, by index.third — the third element.last — the last element, using a negative index.Run your code to see the output, then press Submit.
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)
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.