Lists are Python's ordered, mutable sequence type, and the page focuses on indexing, slicing, mutation, copies, and the mistakes that show up when one list alias changes another.
Focus on how list operations change the same object, when slicing returns a new list, and why `sort()` and `sorted()` behave differently.
A list is an ordered, mutable collection that can hold items of any data type. Lists are one of the most used data structures in Python.
empty = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "mango"]
mixed = [1, "hello", 3.14, True, None]
matrix = [[1, 2, 3], [4, 5, 6]]
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
print(len(fruits)) # 3
print(type(fruits)) # <class 'list'>
Lists use zero-based indexing. Negative indexes count from the end.
fruits = ["apple", "banana", "orange", "grapes", "mango"]
print(fruits[0]) # apple
print(fruits[2]) # orange
print(fruits[-1]) # mango (last item)
print(fruits[-2]) # grapes
# Slicing: list[start:stop:step]
print(fruits[1:3]) # ['banana', 'orange']
print(fruits[:3]) # ['apple', 'banana', 'orange']
print(fruits[2:]) # ['orange', 'grapes', 'mango']
print(fruits[::2]) # ['apple', 'orange', 'mango']
print(fruits[::-1]) # reversed list
# Nested list
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2]) # 6
fruits = ["apple", "banana", "orange"]
fruits[1] = "mango" # change single item
fruits.append("pear") # add to end
fruits.insert(1, "cherry") # insert at index 1
fruits.extend(["fig", "plum"]) # add multiple items
# Concatenate
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b # [1, 2, 3, 4, 5, 6]
print([0] * 5) # [0, 0, 0, 0, 0]
fruits = ["apple", "banana", "orange", "banana", "mango"]
fruits.remove("banana") # removes first occurrence
last = fruits.pop() # removes and returns last item
item = fruits.pop(1) # removes and returns item at index 1
nums = [10, 20, 30, 40, 50]
del nums[2] # delete by index
del nums[1:3] # delete a slice
nums.clear() # remove all items
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# With index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# List comprehension
upper = [f.upper() for f in fruits]
print(upper) # ['APPLE', 'BANANA', 'MANGO']
# Filter with comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8]
| Method | Description |
|---|---|
| append(x) | Add item to end |
| insert(i, x) | Insert at index i |
| extend(iterable) | Add all items from iterable |
| remove(x) | Remove first occurrence of x |
| pop(i) | Remove & return item at index (default: last) |
| clear() | Remove all items |
| index(x) | Return index of first occurrence |
| count(x) | Count occurrences of x |
| sort() | Sort in place |
| reverse() | Reverse in place |
| copy() | Return shallow copy |
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(nums.count(1)) # 2
print(nums.index(5)) # 4
nums.sort()
print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
nums.reverse()
print(nums) # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() returns new list
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # [3, 1, 4, 1, 5] unchanged
print(sorted_list) # [1, 1, 3, 4, 5]
# Sort by key
words = ["banana", "apple", "cherry", "fig"]
words.sort(key=len)
print(words) # ['fig', 'apple', 'banana', 'cherry']
# Copy vs reference
a = [1, 2, 3]
b = a.copy() # independent copy
b.append(4)
print(a) # [1, 2, 3] unchanged
0 of 2 checked
Try this next
0 of 3 completed
Lists are mutable (can be changed after creation) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Use tuples for fixed data, lists for data that changes.
The fastest way is: <code>unique = list(set(mylist))</code>. Note this does not preserve order. To preserve order: <code>unique = list(dict.fromkeys(mylist))</code>.
Use the key parameter: <code>sorted(people, key=lambda x: x["age"])</code> or <code>people.sort(key=lambda x: x["name"])</code>.
Explore 500+ free tutorials across 20+ languages and frameworks.