Python Collections: List, Tuple, Set, and Dictionary
Python provides several built-in collection types to store and manage data efficiently. The most
commonly used are List, Tuple, Set, and Dictionary. Below are their definitions, properties,
examples, and differences.
1. List
Definition: An ordered, mutable collection that can store duplicate elements.
Syntax: [element1, element2, ...]
Properties:
- Maintains insertion order
- Allows duplicates
- Mutable (can be changed after creation)
Example:
my_list = [10, 20, 30, 20]
print(my_list) # [10, 20, 30, 20]
my_list.append(40)
my_list[1] = 25
print(my_list) # [10, 25, 30, 20, 40]
2. Tuple
Definition: An ordered, immutable collection that can store duplicate elements.
Syntax: (element1, element2, ...)
Properties:
- Maintains insertion order
- Allows duplicates
- Immutable (cannot be changed after creation)
Example:
my_tuple = (10, 20, 30, 20)
print(my_tuple) # (10, 20, 30, 20)
print(my_tuple[2]) # 30
3. Set
Definition: An unordered, mutable collection of unique elements.
Syntax: {element1, element2, ...}
Properties:
- No duplicate elements
- Unordered (no indexing)
- Mutable
Example:
my_set = {10, 20, 30, 20}
print(my_set) # {10, 20, 30}
my_set.add(40)
my_set.remove(20)
print(my_set) # {40, 10, 30}
4. Dictionary
Definition: An unordered collection of key-value pairs.
Syntax: {key1: value1, key2: value2, ...}
Properties:
- Keys must be unique and immutable
- Values can be duplicated
- Maintains insertion order (Python 3.7+)
- Mutable
Example:
my_dict = {"name": "John", "age": 25, "city": "Delhi"}
print(my_dict["name"]) # John
my_dict["age"] = 30
my_dict["country"] = "India"
print(my_dict)
Differences Between List, Tuple, Set, and Dictionary
Feature List Tuple Set Dictionary
Order Ordered Ordered Unordered Ordered (3.7+)
Mutable Yes No Yes Yes
Duplicates Allowed Allowed Not Allowed Keys: No, Values: Yes
Indexing Yes Yes No Keys act as index
Syntax [] () {} {key: value}
Use Case Sequential data Fixed sequence Unique items Key-value mapping