Sobes.tech
Junior
211

What is a container in the context of Python programming?

Answer from AI

sobes.tech AI

In the context of Python, a container is an object that can hold other objects and provides ways to access them. They allow grouping data.

Main types of built-in containers in Python:

  • Sequence types: Ordered collections of elements. Elements are accessible by index.

    • list: mutable, can contain elements of different types.
    • tuple: immutable, can contain elements of different types.
    • str: immutable, sequence of characters.
    • bytes: immutable, sequence of bytes.
    • bytearray: mutable, sequence of bytes.
  • Set types: Unordered collections of unique elements.

    • set: mutable.
    • frozenset: immutable.
  • Mapping types: Store key-value pairs. Keys must be unique and hashable.

    • dict: mutable.

Examples:

# list
my_list = [1, 'apple', 3.14]

# tuple
my_tuple = (1, 2, 3)

# dict
my_dict = {'name': 'Alice', 'age': 30}

# set
my_set = {1, 2, 3, 1} # set will contain only {1, 2, 3}

Container types support various operations such as iteration, membership testing, and length retrieval.