SoFunction
Updated on 2025-04-13

Python container types list/dictionary/tuple/collection method

1. List - Ordered Variable Sequence

1.1 Basic Features

  • Orderly arranged: Elements are stored in the order of insertion
  • Variable Type: Support in-situ modification
  • Repeat allowed: Elements with the same value can be stored
  • Heterogeneous data: Can mix different types of elements
# Create methodfruits = ['apple', 'banana', 'cherry']
numbers = list(range(1, 6))      # [1,2,3,4,5]
mixed = [1, 'text', True, 3.14]  # Mixed Types

1.2 Core Operations

operate Example illustrate
Index access fruits[0] → ‘apple’ Support negative index (the last of the -1 table)
Slice operation numbers[1:3] → [2,3] Head and not tail
Add elements (‘orange’) Added at the end
Insert element (1, ‘mango’) Insert at the specified location
Delete elements del fruits[2] Delete the specified index element
List comprehension [x**2 for x in numbers] Quickly generate new lists

1.3 Application scenarios

  • Data collection and batch processing
  • Implement stack/queue data structure
  • Temporary storage of calculation results
  • CSV file line record processing

2. Dictionary (Dict) - Key-value pair mapping

2.1 Basic Features

  • Key-value pair storage:{key: value} structure
  • Unordered arrangement(Python 3.7+ keeps insertion order)
  • The key must be hashable(Immutable type)
  • Quick search:O(1) Time complexity
# Create methodperson = {'name': 'Alice', 'age': 25}
scores = dict(math=90, english=85)  # Keyword creationempty_dict = {}  # Empty Dictionary

2.2 Core operations

operate Example illustrate
Get the value person[‘name’] → ‘Alice’ KeyError processing is recommended to use get()
Add/Modify person[‘gender’] = ‘female’ Automatically add or update
Delete key del person[‘age’] Delete the specified key
Iterate over key-value pairs for k, v in (): Get key values ​​at the same time
Dictionary derivation {k:v*2 for k,v in ()} Quickly generate new dictionary

2.3 Application scenarios

  • Configuration file storage
  • JSON data processing
  • Cache system implementation
  • Database record representation

3. Tuple - Immutable Sequence

3.1 Basic Features

  • Immutable Type: Cannot be modified after creation
  • Orderly arranged: Similar list
  • Can hash: Can be used as a dictionary key
  • Performance optimization: More memory saving than list
# Create methodcolors = ('red', 'green', 'blue')
single_element = (42,)  # Pay attention to commascoordinates = tuple([1.2, 3.4])

3.2 Core Applications

  • Function multiple return value encapsulation
  • Protect data from being modified
  • Dictionary key-value storage
  • Format string parameters

4. Set - Unique Element Container

4.1 Basic Features

  • Unordered arrangement: No index concept
  • Element unique: Automatically deduplicate
  • Variable Type: Add or delete elements
  • Mathematical operations: Support for transfer/unification/difference set
# Create methodvowels = {'a', 'e', 'i', 'o', 'u'}
numbers = set([1,2,3,2,1])  # {1,2,3}
empty_set = set()  # Be careful not to use {}

4.2 Core operations

operate Example illustrate
Add elements (‘y’) Added elements
Remove elements (‘i’) KeyError needs to be processed
Set operation set1|set2 → union Support & Intersection - Difference Set
Member testing ‘a’ in vowels → True Quickly judge existence

5. Container comparison summary

characteristic List dictionary Tuples gather
Orderful ❌/✅*
Variability
Repeat elements allow Key unique allow Element unique
Find speed O(n) O(1) O(n) O(1)
Typical Applications Data collection Key-value mapping Data protection Deduplication/operation

*Note: Python 3.7+ dictionary keeps insertion order

6. Nested Use Cases

6.1 List dictionary combination

students = [
    {'name': 'Alice', 'scores': [85, 92, 78]},
    {'name': 'Bob', 'scores': [76, 88, 95]}
]

# Calculate the average scorefor student in students:
    avg = sum(student['scores']) / len(student['scores'])
    print(f"{student['name']} Average score:{avg:.1f}")

6.2 Dictionary value storage collection

department = {
    'sales': {'Alice', 'Bob', 'Charlie'},
    'dev': {'David', 'Eve'}
}

# Merge all department membersall_members = set()
for members in ():
    all_members.update(members)

7. Performance optimization suggestions

  • List vs collection search:
# List search (O(n))if target in big_list: ...
# Convert to collection search (O(1))if target in set(big_list): ...

Dictionary key design:

  • Use immutable types as key
  • Prefer simple data structures

Select the right container:

  • Required Order → List/Tuple
  • Quick Search → Dictionary/Collection
  • Data immutable → Tuple
  • Element unique → collection

8. Advanced skills

Generator expressions: Save memory and process big data

sum(x**2 for x in range(1000000))

Collections module

  • defaultdict: Automatically initialize dictionary values
  • Counter: Fast element count
  • deque: Efficient double-ended queue

*Note: Mastering the characteristics and applicable scenarios of these container types will significantly improve Python programming efficiency and code quality.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.