Week 2
Week 2: Data Structures & Exception Handling
1. Lists, Tuples, Dictionaries, Sets
Lists
Basic List Operations
my_list = [1, 2, 3, 4, 5] my_list.append(6) # Add an element my_list.remove(2) # Remove an element print(my_list) # Output: [1, 3, 4, 5, 6]List Indexing and Slicing
numbers = [10, 20, 30, 40, 50] print(numbers[1]) # Output: 20 print(numbers[-1]) # Output: 50 print(numbers[1:4]) # Output: [20, 30, 40]
Tuples
Tuple Basics
my_tuple = (1, 2, 3, 4) print(my_tuple[1]) # Output: 2Immutable Nature of Tuples
my_tuple = (10, 20, 30) # my_tuple[0] = 100 # This will raise an error since tuples are immutable
Dictionaries
Creating and Accessing Dictionary Elements
Adding and Removing Elements from Dictionary
Sets
Creating and Using Sets
Set Operations (Union, Intersection, Difference)
2. List & Dictionary Comprehensions
List Comprehension Example
Dictionary Comprehension Example
3. Exception Handling (try-except-finally)
Basic Exception Handling
Handling Multiple Exceptions
Using
finallyBlockUsing
elsein Exception HandlingRaising Custom Exceptions
4. File Handling (Reading/Writing Files, CSV, JSON)
Writing to a File
Reading from a File
Reading a File Line by Line
Writing and Reading CSV Files
Writing and Reading JSON Files
Last updated