len returns the number of elements in a list:
tasks = ["email", "report", "review"]
print(len(tasks))
Output:
3
An empty list is written [] and has length 0.
The in operator checks whether a value is an element of a list. It produces a boolean:
print("report" in tasks)
print("meeting" in tasks)
Output:
True
False
not in is the opposite check: "meeting" not in tasks is True.
len also works on strings — len("Ada") is 3. in on strings is covered in the strings section.
is_registered with two parameters: attendees (a list) and name. It returns True when name is in attendees.seats_left with two parameters: attendees and capacity. It returns how many seats remain: capacity minus the number of attendees.seats_left(["Ada", "Grace"], 10) returns 8.
Run your code to see the output, then press Submit.
import unittest
class TestLenAndIn(unittest.TestCase):
def test_registered_name_is_found(self):
self.assertIs(is_registered(["Ada", "Grace"], "Ada"), True)
def test_unregistered_name_is_not_found(self):
self.assertIs(is_registered(["Ada", "Grace"], "Alan"), False)
def test_empty_list_has_no_registrations(self):
self.assertIs(is_registered([], "Ada"), False)
def test_two_attendees_leave_eight_seats(self):
self.assertEqual(seats_left(["Ada", "Grace"], 10), 8)
def test_full_room_leaves_zero_seats(self):
self.assertEqual(seats_left(["Ada", "Grace"], 2), 0)
def is_registered(attendees, name):
return name in attendees
def seats_left(attendees, capacity):
return capacity - len(attendees)
print(is_registered(["Ada", "Grace"], "Ada"))
print(seats_left(["Ada", "Grace"], 10))
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.