What Is a List?
A list is an ordered, mutable (changeable) collection that can hold items of any type — even a mix of types. Lists are one of the most frequently used data structures in Python.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]
Accessing List Items — Indexing
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple (first item)
print(fruits[-1]) # cherry (last item)
Slicing a List
numbers = [10, 20, 30, 40, 50]
print(numbers[1:3]) # [20, 30]
print(numbers[:2]) # [10, 20]
print(numbers[2:]) # [30, 40, 50]
print(numbers[::-1]) # [50, 40, 30, 20, 10] — reversed
Common List Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # add to end → ['apple', 'banana', 'cherry']
fruits.insert(1, "mango") # insert at index → ['apple', 'mango', 'banana', 'cherry']
fruits.remove("banana") # remove by value
fruits.pop() # remove last item
fruits.sort() # sort alphabetically
fruits.reverse() # reverse the order
print(len(fruits)) # number of items
Looping Through a List
courses = ["Python", "Data Science", "AI"]
for course in courses:
print(course)
List Comprehension
A concise way to build a list from an existing sequence in a single line:
squares = [x * x for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Nested Lists
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0]) # 3
List vs Tuple vs Set vs Dict — At a Glance
| Type | Ordered | Mutable | Duplicates |
|---|---|---|---|
| List | Yes | Yes | Allowed |
| Tuple | Yes | No | Allowed |
| Set | No | Yes | Not allowed |
| Dict | Yes (insertion order) | Yes | Keys unique |
Key Takeaways
- Lists are ordered and mutable — you can add, remove, and change items after creation
- Use indexing (
list[0]) and slicing (list[1:3]) to access items - List comprehensions offer a quick, readable way to build a new list from a sequence