ラベル collection containers の投稿を表示しています。 すべての投稿を表示
ラベル collection containers の投稿を表示しています。 すべての投稿を表示

2025年3月19日水曜日

What is collection containers in Python and how to use them

In Python, "collection containers" refer to data structures that can hold multiple items. Python provides several built-in collection containers, and the collections module extends these with specialized container types. Here's a breakdown:  

Built-in Collection Containers:

These are fundamental to Python and readily available:

  • Lists:
    • Ordered, mutable sequences of items.  
    • Items can be of different data types.  
    • Created using square brackets [].
    • Example: my_list = [1, "hello", 3.14]
  • Tuples:
    • Ordered, immutable sequences of items.  
    • Similar to lists, but their elements cannot be changed after creation.  
    • Created using parentheses ().
    • Example: my_tuple = (1, "world", 2.71)
  • Dictionaries:
    • Unordered collections of key-value pairs.
    • Keys must be unique and immutable.  
    • Created using curly braces {}.
    • Example: my_dict = {"name": "Alice", "age": 30}
  • Sets:
    • Unordered collections of unique items.  
    • Useful for membership testing and removing duplicates.  
    • Created using curly braces {} or the set() constructor.
    • Example: my_set = {1, 2, 3, 4}

collections Module:

This module provides specialized container types that offer additional functionality:  

  • Counter:
    • A dictionary subclass for counting hashable objects.  
    • Useful for counting the occurrences of items in a list or other iterable.  
    • Example:
      Python
      from collections import Counter
      counts = Counter(["a", "b", "a", "c", "b", "b"])
      print(counts)  # Output: Counter({'b': 3, 'a': 2, 'c': 1})
      
  • namedtuple:
    • A factory function for creating tuple subclasses with named fields.  
    • Makes tuples more readable and self-documenting.  
    • Example:
      Python
      from collections import namedtuple
      Point = namedtuple("Point", ["x", "y"])
      p = Point(10, 20)
      print(p.x) #output: 10
      
  • defaultdict:
    • A dictionary subclass that calls a factory function to supply missing values.  
    • Simplifies code when dealing with dictionaries where keys may not exist.
    • Example:
      Python
      from collections import defaultdict
      my_defaultdict = defaultdict(int)
      my_defaultdict["a"] += 1
      print(my_defaultdict["a"]) #output: 1
      print(my_defaultdict["b"]) #output: 0
      
  • deque:
    • A double-ended queue, which is a list-like container with fast appends and pops on either end.  
    • Efficient for implementing queues and stacks.
    • Example:
      Python
      from collections import deque
      d = deque([1, 2, 3])
      d.append(4)
      d.appendleft(0)
      print(d) #output: deque([0, 1, 2, 3, 4])
      
  • ChainMap:
    • A dict-like class for creating a single view of multiple mappings.  
    • Useful for managing multiple dictionaries as a single unit.  

How to Use Them:

  • Import the necessary module (if needed).
  • Create an instance of the container.
  • Use the container's methods to add, remove, or access items.

These collection containers are essential tools for Python programmers, providing efficient and convenient ways to manage and manipulate data.