Loading notes...
Loading notes...
Class 11 • Chapter 8
Chapter 8 introduces Lists, Python's most versatile data structure. It covers list creation, the concept of mutability, traversal techniques, and essential list methods.
A variable can only hold a single piece of data. If you needed to store the grades of 100 students, creating 100 variables (`grade1`, `grade2`...) would be a nightmare. Python solves this with Lists. A List is a built-in data structure that allows you to store an ordered collection of multiple items inside a single variable. Lists are incredibly powerful, flexible, and heavily used in almost every Python script.
8.1 Creating and Accessing Lists
Lists are created by placing elements inside square brackets `[]`, separated by commas. Unlike arrays in C or Java, Python lists are heterogeneous, meaning they can hold items of completely different data types simultaneously.
# A homogeneous list (all integers)
scores = [95, 82, 75, 100]
# A heterogeneous list (mixed data types)
student_record = ["Basant", 17, True, 88.5]
# Accessing elements uses the exact same Indexing rules as strings
print(scores[0]) # Output: 95
print(student_record[-1]) # Output: 88.58.2 Lists are Mutable
CRITICAL RULE: Unlike strings, Lists are Mutable. This means you can freely change, add, or remove elements within the list without creating a brand new list in memory.
fruits = ["Apple", "Banana", "Cherry"]
# Modifying an existing element in place
fruits[1] = "Blueberry"
print(fruits) # Output: ['Apple', 'Blueberry', 'Cherry']8.3 Traversing a List
Traversing means visiting every single element in the list, one by one. This is overwhelmingly done using a `for` loop.
colors = ["Red", "Green", "Blue"]
# The elegant Pythonic way to traverse
for color in colors:
print(color)
# Traversing using index (Useful if you need to know the index number)
for i in range(len(colors)):
print(f"Index {i} holds {colors[i]}")8.4 List Operations
Just like strings, lists support concatenation, replication, and slicing.
8.5 Built-in List Methods
Because lists are mutable, many list methods modify the list in-place and return `None`.