📊

Understanding 2D Collections in Python

Nov 5, 2024

Lecture on 2D Collections in Python

Introduction to 2D Lists

  • 2D Lists: A two-dimensional list is a list made up of lists.
    • Useful for grid or matrix data (e.g., Excel spreadsheet).
  • Flexibility: 2D lists are more flexible compared to 2D tuples.

Creating 2D Lists

  • Example Lists:
    • Fruits: [apple, orange, banana, coconut]
    • Vegetables: [celery, carrots, potatoes]
    • Meats: [chicken, fish, turkey]
  • Creating a 2D List:
    • Combine individual lists into one outer list (e.g., groceries = [fruits, vegetables, meats]).

Accessing Elements in 2D Lists

  • Print Entire 2D List: Lists are separated by commas within square brackets.
  • Accessing Rows:
    • groceries[0] for fruits list.
    • groceries[1] for vegetables list.
    • groceries[2] for meats list.
  • Accessing Elements within Rows:
    • Use two indices: groceries[row][column].
    • Example: groceries[0][0] gives apple.
    • Out of range index will cause an error.

Iterating Over 2D Lists

  • Using Nested Loops:
    • Outer loop iterates over rows.
    • Nested loop iterates over elements within each row.
    • Adjust print statements for a grid-like structure by managing newline characters.

Other 2D Collections

  • 2D Tuples: Tuples can be used for 2D collections.
    • Example: Numpad as a 2D tuple.
    • Tuples are ordered and unchangeable, hence faster than lists.
  • 2D Sets: Possible but not suitable for ordered data as sets are unordered.

Exercise: Creating a 2D Keypad

  • Data Type Selection:
    • Tuple preferred for ordered, unchangeable elements.
  • Constructing a 2D Tuple for Numpad:
    • Four rows: (1,2,3), (4,5,6), (7,8,9), (*,0,#).
    • Use loops to print in grid format similar to a telephone keypad.*

Conclusion

  • Summary: 2D collections (lists, tuples, or sets) are essential for handling grid or matrix data in Python.
  • Flexibility and Performance: Choose between lists and tuples based on flexibility needs and performance considerations.