Python Collections
Python Collections
The collection Module in Python provides different types of containers. A Container is an object
that is used to store different objects and provide a way to access the contained objects and iterate over
them.
Python Collections
Python provides several built-in data structures that help in storing and managing data efficiently.
These data structures are categorized into primitive and non-primitive (collection data types).
Tuple:
A tuple in Python is an ordered collection of elements, meaning that the sequence in which items
are stored in the tuple is preserved. When you access elements using indexing, they always appear in the
same order as they were defined.
Tuples in Python have limited built-in methods compared to lists because they are immutable (cannot
be modified). However, here are some essential tuple methods and functions useful for problem-solving:
SET:
Sets in Python are unordered, mutable (modifiable), and unique collections. Unlike tuples, sets
do not maintain insertion order and do not allow duplicate values.
1. add() – Adds an element to the set
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
List:
A list in Python is a mutable, ordered, and indexed collection that allows duplicate values. Lists are
one of the most commonly used data structures in Python due to their flexibility and efficiency.
lst1.append(lst2)
print(lst1) # Output: [1, 2, 3, [4, 5]]
lst3 = [1, 2, 3]
lst3.extend(lst2)
print(lst3) # Output: [1, 2, 3, 4, 5]
✅ append() keeps the entire list as a single element. Adds entire thing as it is without unpacking.
✅ extend() unpacks and adds elements one by one.
Dictionary:
A dictionary in Python is an unordered, mutable, and indexed collection that stores key-value
pairs. Unlike lists, which use integer indices, dictionaries allow us to access values using unique keys.
Dictionary Methods
🔹 1. keys() – Get all keys
student = {"name": "Alice", "age": 21, "course": "CS"}
print(student.keys()) # Output: dict_keys(['name', 'age', 'course'])
Use Case Sequential Data Immutable Data Unique Items Key-Value Lookup
Final Thought