Chapter Review Questions

Chapter Review Questions#

Note

Source: Python-specific — no direct equivalent in the C# edition. Questions cover Python tuple syntax, immutability, unpacking, and common use cases.

  1. What is the key difference between a tuple and a list?

  2. Single-element tuples.

    1. How do you create a tuple with exactly one element?

    2. What does (42) create instead, and why?

  3. Is the following valid Python? What does it create?:

    t = 1, 2, 3
    
  4. What error occurs when you try to assign to an element of a tuple?

  5. Write one line of Python that swaps the values of variables x and y without using a temporary variable.

  6. Extended unpacking.

    Given:

    data = (10, 20, 30, 40)
    

    Write an unpacking statement that assigns 10 to first, 40 to last, and [20, 30] to middle.

  7. Why can a tuple be used as a dictionary key but a list cannot?

  8. The zip() function.

    1. What does zip([1, 2, 3], ["a", "b", "c"]) produce?

    2. Write a for loop that prints each pair on its own line.

  9. When would you choose a tuple over a list?

    1. Give one example where a tuple is the natural choice.

    2. Give a second, different example.

  10. What is the output of:

    a, b, c = (5, 10, 15)
    a, b = b, a
    print(a, b, c)