Chapter Review Questions

Chapter Review Questions#

Note

Source: Adapted from the C# edition (lists/reviewlists.rst and arrays/reviewarrays.rst). Questions updated for Python list syntax and methods.

  1. What is the index of the first element of a list? The last?

  2. How do you get the number of elements in a list named data?

  3. Two ways to sort.

    1. What does list.sort() do?

    2. What does sorted(lst) do?

    3. When would you prefer each?

  4. What does data[2:5] return if data = [10, 20, 30, 40, 50, 60]?

  5. What does data[-1] refer to?

  6. What is the difference between list.append(x) and list.extend(other)?

  7. What error is raised if you call data.remove(x) and x is not in the list?

  8. The pop() method.

    1. What does data.pop() return if data = [1, 2, 3]?

    2. What does data contain after the call?

  9. Write a list comprehension that produces the squares of odd numbers from 1 to 9: [1, 9, 25, 49, 81].

  10. Aliasing.

    a = [1, 2, 3]
    b = a
    b.append(4)
    print(a)
    
    1. What is printed?

    2. Why is the output surprising?

    3. How would you make a true independent copy of a?

  11. Linear search vs. binary search.

    1. What is the time complexity of each?

    2. What additional requirement does binary search impose on the list?

  12. Trace through one complete pass of bubble sort on [5, 3, 1, 4] and show the state of the list after each swap.