2D Collections in Python
Overview
- 2D collections represent data in a grid or matrix format (e.g., like an Excel spreadsheet).
- Mainly involves working with 2D lists, but can include 2D tuples and sets.
2D Lists
- A 2D list is a list made up of lists.
- Useful for organizing data into rows and columns.
Creating a 2D List
- One-dimensional lists: Start with individual lists, e.g., fruits, vegetables, meats.
- Combine into a 2D list: Add these lists as elements within an outer list, forming a 2D structure.
Accessing Elements
- Single index: Returns an entire row (e.g.,
groceries[0] returns the 'fruits' list).
- Double index: Access specific elements (like coordinates), e.g.,
groceries[0][0] for 'apple'.
Printing a 2D List
- Printing directly displays the entire structure with inner lists separated by commas.
- Align elements to mimic a grid structure with rows and columns.
Modifying a 2D List
- Indices allow modification of specific elements.
Iterating Over a 2D List
- Nested loops: Use to iterate through rows and elements within each row.
for collection in groceries:
for food in collection:
print(food, end=' ')
print() # For new line after each row
Other 2D Collections
- 2D Tuples: Tuples made up of tuples; immutable and ordered.
- 2D Sets: Not typically used since sets are unordered.
Example: 2D Tuple for a Phone Keypad
- Define a 2D tuple named
numpad.
- Structure:
((1, 2, 3), (4, 5, 6), (7, 8, 9), ('*', 0, '#'))
- Iterate over with loops to print in a grid format.*
Conclusion
- 2D collections are versatile for organizing and accessing data in a structured format.
- Understanding these fundamentals helps in effectively managing data in programming tasks.
Note: Choose between lists, tuples, or sets based on the data requirements, such as order and mutability.