Loading notes...
Loading notes...
BCA • Chapter 6
Chapter 6 introduces Python's core data structures: Lists (ordered/mutable), Tuples (ordered/immutable), Sets (unordered/unique), and Dictionaries (key-value maps).
Variables holding single values (like `x = 5`) are insufficient for complex software. Python provides four built-in Data Structures to store collections of data: Lists, Tuples, Sets, and Dictionaries. Each structure has unique properties regarding ordering, mutability (changeability), and handling of duplicate data. Choosing the right data structure is the foundation of writing efficient algorithms.
6.1 Lists [ ]
A list is a data structure that is ordered and mutable (changeable). It allows duplicate members. Lists are incredibly versatile and can store heterogeneous data (different data types in the same list). Lists are defined using square brackets `[]`.
# Creating a list
fruits = ["apple", "banana", "cherry", "apple"]
# Lists are ordered and indexed (zero-based)
print(fruits[1]) # Output: banana
# Lists are mutable (you can change elements)
fruits[0] = "mango"
print(fruits) # ['mango', 'banana', 'cherry', 'apple']
# List Methods
fruits.append("orange") # Adds to the end
fruits.insert(1, "kiwi") # Inserts at index 1
fruits.remove("banana") # Removes the first occurrence
popped = fruits.pop() # Removes and returns the LAST element
print(len(fruits)) # Returns the length of the list
fruits.sort() # Sorts the list alphabetically/numerically in placeA powerful feature of Python is List Comprehensions, which offer a shorter syntax to create a new list based on the values of an existing list or iterable.
# Creating a list of squares for even numbers from 0 to 9
# Syntax: [expression for item in iterable if condition]
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # Output: [0, 4, 16, 36, 64]6.2 Tuples ( )
A tuple is a collection which is ordered and unchangeable (immutable). Once a tuple is created, you cannot add, remove, or change elements. Tuples are defined using parentheses `()`. Because they are immutable, tuples are faster and more memory-efficient than lists. They are used to protect data that should not be modified.
# Creating a tuple
coordinates = (10.5, 20.1, 5.0)
# Accessing elements (just like lists)
print(coordinates[0]) # Output: 10.5
# Attempting to change an element raises a TypeError
# coordinates[1] = 99.9 <-- ERROR
# Single element tuple MUST have a trailing comma
single = (5,)
print(type(single)) # <class 'tuple'>
# Tuple Unpacking
x, y, z = coordinates
print(f"X is {x}, Y is {y}")6.3 Sets { }
A set is a collection which is unordered, unindexed, and does not allow duplicate elements. Sets are defined using curly braces `{}`. Because sets are backed by a hash table, checking if an item exists in a set (`in` operator) is blazingly fast (O(1) time complexity).
# Creating a set
ids = {101, 102, 103, 101, 102}
print(ids) # Output: {101, 102, 103} (Duplicates automatically removed!)
# Note: To create an empty set, you MUST use set(), not {}
empty_set = set()
# Set Methods
ids.add(104)
ids.remove(101)
# Mathematical Set Operations
setA = {1, 2, 3, 4}
setB = {3, 4, 5, 6}
print(setA.union(setB)) # {1, 2, 3, 4, 5, 6} (or setA | setB)
print(setA.intersection(setB)) # {3, 4} (or setA & setB)
print(setA.difference(setB)) # {1, 2} (or setA - setB)6.4 Dictionaries {key: value}
A dictionary is a collection which is ordered (as of Python 3.7), changeable, and does not allow duplicate keys. Dictionaries store data in `key: value` pairs. They are incredibly powerful for mapping relationships. Keys must be immutable types (like strings, numbers, or tuples), while values can be anything.
# Creating a dictionary
student = {
"name": "Basant",
"age": 21,
"course": "BCA"
}
# Accessing values via keys
print(student["name"]) # Output: Basant
# Using get() is safer; it returns None if the key doesn't exist instead of crashing
print(student.get("grade", "Not Graded")) # Output: Not Graded
# Modifying and Adding
student["age"] = 22 # Updates existing key
student["college"] = "DU" # Adds a new key-value pair
# Removing
del student["course"]
# Iterating through a dictionary
for key, value in student.items():
print(f"{key}: {value}")