Lists, Tuples, Sets and Dictionary - Study Notes
Chapter Summary
This chapter explores the four primary built-in data collections in Python: Lists, Tuples, Sets, and Dictionaries. These structured data types allow programmers to group multiple items together under a single identifier. A List is an ordered, mutable sequence. A Tuple is an ordered, immutable sequence. A Set is an unordered collection of unique elements. A Dictionary is an unordered collection of key-value pairs where each key maps to a specific value. Mastering these collections is critical for managing data, implementing algorithms, and building robust software applications in Python.
Learning Objectives
- Understand the fundamental differences and similarities between Lists, Tuples, Sets, and Dictionaries.
- Create and manipulate Lists using methods such as append, extend, insert, and remove.
- Work with Tuples, recognizing their immutable nature and utilizing tuple assignment.
- Perform mathematical set operations like Union, Intersection, Difference, and Symmetric Difference.
- Create, access, update, and delete elements in Dictionaries using unique keys.
- Analyze performance trade-offs, such as the speed advantage of Tuples over Lists.
Key Concepts and Definitions
Lists
A List is a sequence of elements enclosed within square brackets [ ]. Lists are ordered, meaning elements stay in their inserted position. They are mutable, allowing elements to be replaced, added, or deleted during execution. Elements are indexed starting from zero for positive subscripts, and from -1 for negative subscripts (reverse indexing).
Tuples
A Tuple is a sequence of elements separated by commas and optionally enclosed within parentheses ( ). Tuples are ordered but immutable, meaning their elements cannot be changed after creation. This immutability ensures data integrity and enables faster execution compared to Lists.
Sets
A Set is an unordered collection of distinct, unique elements enclosed in curly braces { }. Sets do not allow duplicate values. They are highly efficient for membership testing and eliminating duplicates from sequences.
Dictionaries
A Dictionary is a mutable collection of key-value pairs enclosed in curly braces { }. Each key must be unique and is separated from its associated value by a colon (:). Keys act as customized indexes for rapid data lookup.
Worked Methods
1. Creating and Updating Lists
Lists are created using square brackets. To add a single element, use the append() method. To add multiple elements, use the extend() method. To insert an element at a specific index, use insert(index, element). Elements can be updated via assignment: list_var[index] = new_value.
2. List Comprehension
List comprehension offers a compact syntax for generating new lists. The general structure is [expression for variable in range]. For example, to generate a list of squares: squares = [x**2 for x in range(1, 11)].
3. Tuple Assignment
Tuple assignment allows variables on the left side of the assignment operator to be mapped to values on the right. For example: (x, y, z) = (10, 20, 30) assigns 10 to x, 20 to y, and 30 to z.
4. Set Operations
Sets support mathematical operations:
- Union (|): Combines all unique elements from both sets.
- Intersection (&): Finds elements common to both sets.
- Difference (-): Finds elements present in the first set but not in the second.
- Symmetric Difference (^): Finds elements in either set, excluding common ones.
Common Exam Traps
- The Singleton Tuple: Creating a tuple with a single element requires a trailing comma (e.g., t = (10,)). Without the comma, Python treats it as a standard integer or string in parentheses.
- Tuple Immutability: Attempting to change an element in a tuple (e.g., t = 5) results in a TypeError. Remember that while the tuple itself is immutable, it can be deleted entirely using the del statement.
- Set Duplication: Adding duplicates to a set does not raise an error, but Python silently removes them. Always remember that sets store only unique items.
- Dictionary Key Uniqueness: Dictionary keys must be unique. If you assign a value to an existing key, the old value is overwritten without warning.
Exam Tips
- Always remember the start and end rules of the range(start, stop, step) function: it counts up to stop - 1.
- Negative indexing is incredibly useful for accessing elements from the end of a list or tuple. Index -1 refers to the very last element.
- Pay close attention to bracket styles in questions: square brackets [] represent Lists, parentheses () represent Tuples, and curly braces {} represent Sets or Dictionaries.
- Use type() in your answers to identify the data structure of an object when debugging code.