List
A list is the most versatile data structure in Python. Lists are mutable (can be changed), can hold different data types, and their elements are accessed using indices.
Imagine a train with carriages that can each hold different cargo. A list in Python is exactly like that — an ordered container that can hold numbers, text, and even other lists inside. Because lists are mutable, we can add, remove, or modify elements at any time. This is what makes lists different from tuples, which are immutable.
Lists also support slicing and list comprehensions. Slicing lets you take a certain portion of a list with simple syntax. List comprehensions are a signature Python feature that lets you create a new list in a single line of code — combining a loop and a condition in a concise and elegant expression.
Code Example
# Creating a list
fruits = ["apple", "mango", "orange"]
numbers = [1, 2, 3, 4, 5]
# Modifying
fruits.append("durian") # add at end
fruits.insert(1, "banana") # insert at index 1
fruits.remove("mango") # remove by value
removed = fruits.pop(0) # remove & take index 0
# Slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::2]) # [1, 3, 5]
# List Comprehension
squares = [x**2 for x in range(6)]
print(squares) # [0, 1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Code Explanation
The fruits list is filled with three strings. append("durian") adds an element to the very end. insert(1, "banana")" inserts "banana" at index 1 (between "apple" and "mango").remove("mango")" removes the element based on its value. pop(0)" removes the element at index 0 and returns its value to the variableremoved`.
Slicing numbers[1:4] takes indices 1 through 3 (4 is not included). numbers[::2] takes every element with a step of 2.
The list comprehension [x**2 for x in range(6)] creates a new list by squaring each number 0-5. The next line [x for x in range(10) if x % 2 == 0] filters to even numbers only.
Everyday Example
A to-do list application. Each task is added to the list, can be marked as done (removed), and is displayed with sequential numbering.
tasks = []
tasks.append("Learn Python")
tasks.append("Do homework")
tasks.append("Exercise")
print("To-Do List:")
for i, t in enumerate(tasks, 1):
print(f"{i}. {t}")
done = tasks.pop(1)
print(f"Done: {done}")
print(f"Remaining tasks: {tasks}")
Summary
Lists are the most flexible data structure in Python — mutable, able to hold anything, and equipped with powerful methods and slicing. Combined with concise list comprehensions, lists become the main weapon for managing collections of data.