Python List Type
What Is a List?
A list is a mutable sequence type in Python, used to store collections of items. Lists can hold items of any type, and the items can be changed, added, or removed after the list is created.
Creating Lists
You can create a list using square brackets or the list()
constructor:
empty = []
numbers = [1, 2, 3]
mixed = [1, "hello", 3.14, True]
from_iterable = list("abc") # ['a', 'b', 'c']
Accessing and Modifying Lists
You can access items by index, slice lists, and modify their contents:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'cherry'
fruits[1] = "orange" # Change 'banana' to 'orange'
print(fruits[1:]) # ['orange', 'cherry']
Slicing Lists
Slicing lets you extract a part (a "slice") of a list by specifying a start, stop, and optional step value. The result is a new list containing the selected elements.
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3] (from index 1 up to, but not including, 4)
print(numbers[:3]) # [0, 1, 2] (from start up to index 3)
print(numbers[3:]) # [3, 4, 5] (from index 3 to the end)
print(numbers[::2]) # [0, 2, 4] (every second element)
print(numbers[-3:]) # [3, 4, 5] (last three elements)
print(numbers[::-1]) # [5, 4, 3, 2, 1, 0] (reversed list)
- The syntax is
list[start:stop:step]
. - Omitting
start
starts from the beginning; omittingstop
goes to the end; omittingstep
uses a step of 1. - Slicing never raises an error if the indices are out of range; it just returns as much as possible.
Common List Operations
Lists support many operations:
numbers = [1, 2, 3]
print(len(numbers)) # 3
print(numbers + [4, 5]) # [1, 2, 3, 4, 5] (concatenation)
print(numbers * 2) # [1, 2, 3, 1, 2, 3] (repetition)
print(2 in numbers) # True (membership)
List Methods
Lists have many built-in methods for adding, removing, and modifying items:
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
lst.insert(1, 10) # [1, 10, 2, 3, 4, 5, 6]
lst.remove(10) # [1, 2, 3, 4, 5, 6]
lst.pop() # 6, list is now [1, 2, 3, 4, 5]
lst.clear() # []
lst = [3, 1, 2]
lst.sort() # [1, 2, 3]
lst.reverse() # [3, 2, 1]
lst.copy() # [3, 2, 1]
Iterating Over Lists
You can loop through lists using a for
loop:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
List Comprehensions
List comprehensions provide a concise way to create lists:
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Copying Lists
To make a shallow copy of a list:
original = [1, 2, 3]
copy1 = original.copy()
copy2 = list(original)
copy3 = original[:]
Nested Lists
Lists can contain other lists:
matrix = [[1, 2], [3, 4]]
print(matrix[0][1]) # 2
Summary
- Lists are mutable sequences for storing collections of items.
- Support indexing, slicing, and many built-in methods.
- Use list comprehensions for concise list creation.
- Lists can contain any type, including other lists.