Unit III: Data Structures and Modules
1. Lists
A List is an ordered, mutable collection of items that can be of different data types.
- Indexing: Lists use zero-based indexing to access elements.
- Operations: Supports concatenation (joining lists), repetition (multiplying elements), membership (checking if item exists), and slicing (extracting parts of a list).
- Traversal: Lists can be traversed using loops to process each element sequentially.
- Nested Lists: Lists can contain other lists as elements.
- Built-in Methods: Python provides various methods to manipulate lists, such as append(), extend(), and insert().
2. Tuples
A Tuple is an ordered, immutable sequence of items. Once created, its elements cannot be changed.
- Indexing: Similar to lists, tuples use indexing to access specific items.
- Operations: Supports concatenation, repetition, membership, and slicing.
- Built-in Functions: Common functions include len(), max(), and min().
3. Sets
A Set is an unordered collection of unique elements.
- Creation: Sets are created using curly braces {} or the set() function.
- Modification: Elements can be added or removed, but sets do not support indexing or slicing because they are unordered.
- Operations: Includes mathematical set operations like union, intersection, difference, and symmetric difference.
- Methods: Common methods include add(), remove(), and pop().
4. Dictionaries
A Dictionary is a mapping of unique keys to values.
- Accessing Items: Values are accessed using their associated keys rather than index numbers.
- Mutability: Dictionaries are mutable, allowing for adding new terms or modifying existing items.
- Traversal: You can traverse a dictionary to access keys, values, or key-value pairs using loops.
- Built-in Methods: Includes keys(), values(), and items().
5. Python Modules
A Module is a file containing Python definitions and statements that can be reused in other programs.
- Importing: Modules are imported using the
import <module> statement or the from ... import ... syntax.
- Math Module: A built-in module providing access to mathematical functions like sqrt(), sin(), and cos().
6. String Manipulation
Advanced string handling techniques are vital for data processing.
- Basic Operations: Includes string concatenation and repetition.
- Slicing: Using range indices to extract substrings.
Exam Tips: Data Structure Comparison
Common Mistakes
- Trying to change a tuple element (Tuples are immutable!).
- Using a mutable type (like a list) as a dictionary key.
- Assuming sets maintain the order in which items were added.
Frequently Asked Questions
Q1: When should I use a Tuple instead of a List?
Use a tuple when you have data that should not change throughout the program (e.g., coordinates, constant settings) to ensure data integrity.
Q2: How do I remove duplicates from a list?
The easiest way is to convert the list to a set using set(my_list) and then back to a list, as sets automatically handle unique elements.