🐍
Syllabus / Python Programming / Phase 3: Lists, Tuples, Dictionaries, Sets (Days 11–15)
Beginner

Lists: Creating, Accessing, and Modifying

📂 Phase 3: Lists, Tuples, Dictionaries, Sets (Days 11–15) · Python Programming

A list is Python's most versatile built-in data structure — an ordered, mutable collection that can hold items of any type, including a mix of different types in the same list. Lists are the data structure you will reach for most often in everyday Python code.

Creating a List

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Vishwas", 22, True, 5.9]   # different types in one list — totally valid
empty = []

Accessing Items by Index

Like strings, list indices start at 0, and negative indices count backward from the end.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple  — first item
print(fruits[-1])   # cherry — last item
print(fruits[1])    # banana

Lists Are Mutable

Unlike strings, list elements can be changed in place after creation — this is the single biggest practical difference between the two.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)   # ['apple', 'blueberry', 'cherry']

Adding Items

MethodEffectExample
.append(x)Adds one item to the endfruits.append("mango")
.insert(i, x)Inserts an item at a specific positionfruits.insert(1, "kiwi")
.extend(iterable)Adds every item from another iterable to the endfruits.extend(["fig", "grape"])
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)   # ['apple', 'banana', 'cherry']

fruits.insert(0, "mango")
print(fruits)   # ['mango', 'apple', 'banana', 'cherry']

Removing Items

MethodEffect
.remove(x)Removes the first matching VALUE; raises ValueError if not found
.pop(i)Removes and returns the item at index i (defaults to the last item)
del list[i]Deletes the item at index i without returning it
.clear()Removes every item, leaving an empty list
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")   # removes the VALUE "banana"
print(fruits)              # ['apple', 'cherry']

last_item = fruits.pop()   # removes and returns the LAST item
print(last_item)            # cherry
print(fruits)                # ['apple']

Checking Length and Membership

fruits = ["apple", "banana", "cherry"]
print(len(fruits))            # 3
print("banana" in fruits)     # True
print("mango" not in fruits)  # True

Looping Through a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Lists Can Contain Other Lists

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1])      # [4, 5, 6] — the second inner list
print(matrix[1][2])   # 6 — row index 1, column index 2
Interview tip: Be ready to explain the difference between .remove() and .pop() precisely — remove() searches for a VALUE and deletes its first occurrence, while pop() removes by POSITION (index) and is the only one of the two that returns the removed item.