Lists are the first complex data structures that many Python programmers learn, so it’s important to be clear on how they work. The following activities test your ability to handle data in lists, your knowledge of list methods, and your ability to work with other sequence data types, including tuples and strings.
Practice QuestionsLists are useful data types, as they allow you to write code that works on any number of values contained in a single variable. Use these questions to practice working with this data type.
A list contains multiple values in an ordered sequence. It looks like this: ['cat', 'bat', 'rat', 'elephant']. You can store a list in a variable or pass it to a function, just like any other value. To access an item inside a list, you can reference its numerical index.
1. What is the first index of any list?
2. If a variable named spam contains ['cat', 'bat', 'rat', 'hat'], what does spam[3] evaluate to?
3. If a variable named spam contains ['cat', 'bat', 'rat', 'hat'], what does spam[4] evaluate to?
4. Do all the values in a Python list need to be of the same data type?
5. If a variable named spam contains an empty list, what happens when spam[0] is evaluated?
6. In the expression spam[3], is the [3] also a list?
7. What negative index is equivalent to the index in spam[len(spam) - 1]?
8. What negative index is equivalent to the index in spam[len(spam) - 3]?
9. If a variable named spam contains a list, what is the difference between the statement del spam[0] and the statement del spam?
Using a list is beneficial because it organizes your data in a structure that your program can process much more flexibly. These questions test your ability to work with lists using loops, operators, and functions in the random module.
For questions 10 through 12, determine what the program prints.
10.
spam = ['cat', 'dog', 'moose'] for i in spam: print(i)
11.
spam = ['cat', 'dog', 'moose'] for i in range(len(spam)): print(i)
12.
spam = ['cat', 'dog', 'moose'] for i in range(len(spam)): print(spam[i])
13. If an expression is using the in and not in operators, what data type does it evaluate to?
14. If spam contains the list ['cat', 'dog', 'moose'] and Python runs the statement a, b, c = spam, what does the b variable contain?
15. If Python runs the statement a, b, c = 'cat', what does the b variable contain?
16. Say spam contains a list value and Python runs the statement for a, b in enumerate(spam):. Describe the data that the a and b variables contain.
17. What does the random.choice() function return?
18. What does the random.shuffle() function do?
19. If spam contains the list ['cat', 'dog', 'moose'] and Python runs import random and random.shuffle(spam), what does the expression len(spam) evaluate to?
Augmented assignment operators are shortcuts for changing the value of a variable based on its current value. They exist for the +, -, *, /, and % operators.
20. What does the following program print?
spam = 100 for i in range(5): spam += 1 print(spam)
Rewrite the following assignment statements using the equivalent augmented assignment operators.
A method is the same thing as a function, except it is called on a value. Each data type has its own set of methods. The list data type, for example, has several useful methods for finding, adding, removing, and otherwise manipulating values in a list. Identify the following as either a function or a method.
Answer the following questions about list methods and the sort() function.
33. Both the remove() list method and the del operator can remove items from a list value. How do they work differently?
34. If the spam variable contains a list, running sort(spam) causes an error message. Why?
35. If the spam variable contains a list, what code would rearrange the items in spam in “ASCIIbetical” order?
36. What code could we run so that spam’s contents are sorted in alphabetical order?
For each of the following interactive shell examples, determine what gets printed.
Python can run expressions with Boolean operators a little faster by not examining the right-hand side of the operator under certain circumstances, a practice called short-circuiting.
For each of the following expressions, answer “Hello” if the expression prints "Hello"; answer “Nothing” if it prints nothing. Disregard the Boolean value that the expression evaluates to. You can find the answer by entering the expression into the interactive shell.
Lists aren’t the only data types that represent ordered sequences of values. For example, strings and lists are actually similar if you consider a string to be a “list” of single text characters.
48. List at least two different sequence data types in Python.
49. Why doesn’t the expression 'Zophie'[1] evaluate to Z if Z is the first character in the string 'Zophie'?
50. What does the expression 'Zophie'[-1] evaluate to?
51. What does the expression 'Zophie'[9999] evaluate to?
Determine what each of the following interactive shell examples print.
In Python, variables never contain values. They contain only references to values. The = assignment operator copies only references; it never copies values. For the most part, you don’t need to know these details, but at times, these simple rules have surprising effects, and you should understand exactly what Python is doing. Answer the following questions about references and copying mutable objects.
55. Aside from the square brackets and parentheses, what is the main difference between lists and tuples?
56. Write the code that obtains a list value from the tuple ('cat', 'dog').
57. Write the code that obtains a tuple value from the list ['cat', 'dog'].
58. What happens if you run this code?
spam = ('cat', 'dog', 'moose')
spam[2] = 'cow'59. In Python, variables never contain values. What do they contain?
60. In Python, the = assignment operator never copies values. What does it copy?
61. How many copies of the list value exist in the computer’s memory when you run the following code?
a = ['cat', 'dog', 'moose'] b = a c = a
62. What about for the following?
import copy a = ['cat', 'dog', 'moose'] b = copy.copy(a) c = copy.copy(a)
63. Which method would you call to copy the value [['cat', 'dog'], 'moose']: the copy.copy() function or the copy.deepcopy() function?
Practice ProjectsPractice your knowledge of lists with the following projects.
Write a function named is_pangram(sentence) that accepts a string argument, then returns True if it’s a pangram and False if not. A pangram is a sentence that uses all 26 letters of the alphabet at least once. For example, “The quick brown fox jumps over the yellow lazy dog” is a pangram.
There are several ways to accomplish this task. One way is to have a variable named EACH_LETTER that starts as an empty list. Then, you can loop over the characters in the string argument, convert each to uppercase with the upper() method, and append it to the EACH_LETTER list if it is a letter and doesn’t already exist there. You can tell that a letter in char isn’t already in the EACH_LETTER list because the expression char not in EACH_LETTER will evaluate to True. After looping over each character in the user’s string, you’ll know that the string is a pangram if len(EACH_LETTER) evaluates to 26.
For example, the output of your program could look like this:
Enter a sentence:
The quick brown fox jumps over the yellow lazy dog.
That sentence is a pangram.
Or this:
Enter a sentence:
Hello, world!
That sentence is not a pangram.
Save this program in a file named pangramDetector.py.
Write a function named get_end_coordinates(directions) that accepts a list of north, south, east, and west directions and returns a numeric pair of Cartesian coordinates.
The first part of the program should repeatedly ask the user to enter N, S, E, or W (but should accept the lowercase n, s, e, and w as well) and should collect these inputs in a list. The loop should exit when the user enters a blank string. Next, the program should pass the list to the get_end_coordinates() function.
Going north should increase the y-coordinate by one, while going south should decrease it by one. Likewise, going east should increase the x-coordinate by one, while going west should decrease it by one.
You can represent the coordinates in another list. For example, the function call get_end_coordinates(['N', 'N', 'W']) should return the list [-1, 2], and the function call get_end_coordinates(['E', 'W', 'E', 'E']) should return the coordinates [2, 0]. Your program should print the list returned by get_end_coordinates().
Save this program in a file named coordinateDirections.py.