Lists and choices
A list keeps values in order. names = ["Ada", "Grace"] is a list of two strings.
for name in names visits each one. if len(name) >= 4 keeps the ones that are long enough. chosen.append(name) adds a name to a new list.
A list is the first way this book keeps more than one value under a single name. Order matters. The first item stays first unless you build a new list that changes the order. The tutorial on lists shows indexing, slicing, and methods such as append. This page uses a loop and a test, which is enough to filter a list.
A list is an ordered collection
Square brackets build a list. Commas separate the items. A list can be empty: [] has no items, and a loop over it runs zero times.
len counts items when you give it a list, and characters when you give it a string. len(names) is 3. len("Grace") is 5. len("Bo") is 2. That second use is what the exercise depends on.
- Items keep the order you wrote.
- The same list can hold short names and long names together.
- Building a new list leaves the original list unchanged.
A loop visits each item
for name in names takes the items one at a time, in order. The name name points at the current item. The next pass points it at the next item. When the items run out, the loop ends.
if runs its body only when the test is true. len(name) >= 4 is true for "Grace" and false for "Ada" and "Bo". >= means "greater than or equal." A name of length 4 is kept. A name of length 3 is not.
append adds one item at the end. Because the loop walks the original list from left to right, and append always adds at the end, the kept names stay in their original order. "Grace" comes out after any longer name that appeared before it, and before any longer name that appeared after it.
Worked example
The function below is the whole exercise, written out. Read it against the list ["Ada", "Grace", "Bo"].
chosenstarts empty."Ada"has length 3, so the test fails and nothing is appended."Grace"has length 5, so it is appended.chosenis["Grace"]."Bo"has length 2, so it is skipped.- The function returns
["Grace"], not the original list.
The second call returns []. An empty result is a real answer. It means every name was too short, not that the function failed.
This program cannot be stepped through.
long_names walks the list from left to right and appends names that are long enough. What order are the kept names in?
Click the line that adds a kept name to the new list.
Try the example before you change the exercise.
Write a function named long_names that takes a list of names and returns a new list of the names with at least 4 characters, in the same order.
OutputThe starter returns an empty list so the file runs. That result happens to pass the second check and fail the first. Fill in the loop so both calls return the right list. Return the new list. Do not print it.