Python List
Lists are Python's most versatile and widely-used data structure — an ordered, mutable collection that can hold any mix of data types. From storing student scores to building a shopping cart, lists are everywhere. This chapter covers everything: creating lists, indexing (positive & negative), slicing, all 11 built-in methods, nested lists, sorting, copying and the powerful list comprehension syntax — all with a visual index diagram and runnable examples.
Creating Lists
A list is an ordered, mutable collection enclosed in square
brackets []. Elements are separated by commas. Lists can
hold any mix of data types — integers, strings, floats, booleans, other lists, and even
None — all in the same list.
# Empty list
empty = []
empty2 = list()
# List of integers
scores = [85, 92, 78, 90, 88]
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed types — all valid!
mixed = [42, "hello", 3.14, True, None]
# Duplicate values allowed
dupes = [1, 2, 2, 3, 3, 3]
# List from other iterables
chars = list("Python") # ['P','y','t','h','o','n']
nums = list(range(1,6)) # [1, 2, 3, 4, 5]
# List properties
print(len(scores)) # 5 — number of elements
print(type(scores)) # <class 'list'>
print(min(scores)) # 78
print(max(scores)) # 92
print(sum(scores)) # 433
List Indexing — Positive & Negative
Every element in a list has a position called an index. Python uses
zero-based indexing — the first element is at index
0. Python also supports negative indexing —
-1 is the last element,
-2 the second-to-last, and so on.
fruits = ["apple", "banana", "cherry", "mango", "grape"]
fruits = ["apple", "banana", "cherry", "mango", "grape"]
# Positive indexing (left to right)
print(fruits[0]) # apple — first element
print(fruits[2]) # cherry
print(fruits[4]) # grape — last element (index 4 for 5 items)
# Negative indexing (right to left)
print(fruits[-1]) # grape — last element
print(fruits[-2]) # mango
print(fruits[-5]) # apple — first element
# Modifying an element by index
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry', 'mango', 'grape']
# Checking membership
print("cherry" in fruits) # True
print("orange" not in fruits) # True
# IndexError — out of range
# fruits[10] → IndexError: list index out of range
List Slicing
Slicing extracts a sublist using the syntax
list[start:stop:step]. The
start index is inclusive, the
stop index is exclusive, and
step controls how many positions to advance each time. Any
value can be omitted.
nums = [10, 20, 30, 40, 50, 60, 70]
# [start:stop] — stop is exclusive
print(nums[1:4]) # [20, 30, 40]
# Omit start — from beginning
print(nums[:3]) # [10, 20, 30]
# Omit stop — to end
print(nums[4:]) # [50, 60, 70]
# Full copy
print(nums[:]) # [10, 20, 30, 40, 50, 60, 70]
# Step value
print(nums[::2]) # [10, 30, 50, 70] every other
print(nums[1::2]) # [20, 40, 60] every other starting at 1
# Negative step — reverse
print(nums[::-1]) # [70, 60, 50, 40, 30, 20, 10]
# Negative indices in slice
print(nums[-3:]) # [50, 60, 70]
print(nums[-4:-1]) # [40, 50, 60]
# Practical: reverse a list
print(nums[::-1]) # reversed list
Modifying Lists
Lists are mutable — you can change individual elements, replace multiple elements at once using slice assignment, and even delete elements. Because lists are objects in memory, modifying one reference also affects all other references pointing to the same list.
colors = ["red", "green", "blue", "yellow"]
# Change single element
colors[1] = "lime"
print(colors) # ['red', 'lime', 'blue', 'yellow']
# Change multiple elements via slice assignment
colors[1:3] = ["pink", "purple"]
print(colors) # ['red', 'pink', 'purple', 'yellow']
# Insert extra elements via slice (replace 0 elements)
colors[1:1] = ["orange", "teal"]
print(colors) # ['red', 'orange', 'teal', 'pink', 'purple', 'yellow']
# Delete single element
del colors[0]
print(colors) # ['orange', 'teal', 'pink', 'purple', 'yellow']
# Delete a slice
del colors[1:3]
print(colors) # ['orange', 'purple', 'yellow']
# Mutable means all references see changes!
a = [1, 2, 3]
b = a # b points to same list
b[0] = 99
print(a) # [99, 2, 3] ← a also changed!
# Use .copy() or [:] to avoid this
c = a.copy() # independent copy
c[0] = 0
print(a) # [99, 2, 3] ← a unchanged
All Built-in List Methods
Python lists come with 11 built-in methods. Because lists are mutable, most
methods modify the list in-place and return
None (except pop(),
index(), and count()).
Never do my_list = my_list.append(x) — you'll overwrite the
list with None!
lst = [3, 1, 4, 1, 5]
# append(x) — add one item to the END
lst.append(9)
print(lst) # [3, 1, 4, 1, 5, 9]
# insert(i, x) — insert BEFORE index i
lst.insert(2, 99)
print(lst) # [3, 1, 99, 4, 1, 5, 9]
# extend(iterable) — add all elements of another iterable
lst.extend([10, 20])
print(lst) # [3, 1, 99, 4, 1, 5, 9, 10, 20]
# remove(x) — remove FIRST occurrence of value x
lst.remove(1)
print(lst) # [3, 99, 4, 1, 5, 9, 10, 20] — first 1 removed
# pop(i) — remove and RETURN element at index i (default: last)
val = lst.pop()
print(val, lst) # 20 [3, 99, 4, 1, 5, 9, 10]
val2 = lst.pop(1)
print(val2, lst) # 99 [3, 4, 1, 5, 9, 10]
# index(x) — return index of FIRST occurrence
print(lst.index(5)) # 3
# count(x) — count occurrences of value x
nums = [1, 2, 2, 3, 2]
print(nums.count(2)) # 3
# reverse() — reverses IN-PLACE
lst.reverse()
print(lst) # [10, 9, 5, 1, 4, 3]
# sort() — sorts IN-PLACE (ascending by default)
lst.sort()
print(lst) # [1, 3, 4, 5, 9, 10]
# copy() — return a shallow copy
lst2 = lst.copy()
# clear() — remove ALL elements
lst.clear()
print(lst) # []
Method Reference Table
| Method | Description | Returns |
|---|---|---|
| append(x) | Add x to the end of the list | None |
| insert(i, x) | Insert x before index i | None |
| extend(iter) | Add all elements from iterable to end | None |
| remove(x) | Remove first occurrence of x; raises ValueError if absent | None |
| pop(i=-1) | Remove and return element at index i | element |
| index(x) | Return index of first occurrence of x | int |
| count(x) | Count occurrences of x | int |
| sort() | Sort in-place (ascending default; use reverse=True, key=fn) | None |
| reverse() | Reverse in-place | None |
| copy() | Return a shallow copy | list |
| clear() | Remove all elements | None |
my_list = my_list.append(x) or
my_list = my_list.sort() — these methods modify the list
in-place and return None, overwriting your
variable. Just call my_list.append(x) without assignment.
Sorting, Copying & Nested Lists
Python provides two ways to sort: list.sort() modifies the
list in-place; sorted(list) returns a new sorted list.
Similarly, list.copy() or
list[:] create a shallow copy — sufficient for flat
lists but not for nested lists.
# sort() — in-place, returns None
nums = [5, 2, 8, 1, 9]
nums.sort()
print(nums) # [1, 2, 5, 8, 9]
# sort descending
nums.sort(reverse=True)
print(nums) # [9, 8, 5, 2, 1]
# sorted() — new list, original unchanged
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words) # ['apple', 'banana', 'cherry']
print(words) # ['banana', 'apple', 'cherry'] ← unchanged
# Sort by key — sort by string length
print(sorted(words, key=len)) # ['apple', 'banana', 'cherry']
# Sort list of dicts by a field
people = ["Alice", "Zara", "Bob"]
print(sorted(people, key=str.lower)) # case-insensitive
# Shallow copy vs deep copy
a = [1, 2, 3]
b = a.copy() # shallow copy
b[0] = 99
print(a) # [1, 2, 3] ← unchanged
# Nested lists — 2D list (matrix)
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[1][2]) # 6 — row 1, col 2
print(matrix[0][0]) # 1
# Iterate nested list
for row in matrix:
for val in row:
print(val, end=" ")
print()
# 1 2 3
# 4 5 6
# 7 8 9
List Comprehension
List comprehension is a concise, Pythonic way to create a new list by applying
an expression to each item of an iterable, with an optional filter. The syntax
[expression for item in iterable if condition] replaces
several lines of loop code with a single readable line — and runs faster than an equivalent
for loop.
# Basic: squares of 1–10
squares = [x**2 for x in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# With filter: only even numbers
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Transform: uppercase all strings
fruits = ["apple", "banana", "cherry"]
upper = [f.upper() for f in fruits]
print(upper) # ['APPLE', 'BANANA', 'CHERRY']
# Ternary in comprehension
nums = [-3, 2, -1, 4, -5]
signs = ["pos" if x > 0 else "neg" for x in nums]
print(signs) # ['neg', 'pos', 'neg', 'pos', 'neg']
# Nested: flatten a 2D list
matrix = [[1,2],[3,4],[5,6]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6]
# Filter strings — keep only long words
words = ["hi", "Python", "is", "awesome", "cool"]
long_words = [w for w in words if len(w) > 3]
print(long_words) # ['Python', 'awesome', 'cool']
# Remove duplicates while preserving order
seen = set()
unique = [x for x in [1,2,2,3,1] if x not in seen and not seen.add(x)]
print(unique) # [1, 2, 3]
(x for x in ...) to save memory.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all list examples from this chapter directly in your browser with these free Python environments.
-
A list is an ordered, mutable, duplicate-allowing sequence enclosed in
[]. It can hold any mix of data types. -
Indexing starts at
0. Negative indices count from the end:-1is the last element. -
Slicing:
list[start:stop:step]— stop is exclusive. Use[::-1]to reverse a list. - Lists are mutable — elements can be changed by index, and multiple elements can be replaced via slice assignment. All references to the same list see changes.
-
Key methods:
append(),insert(),extend(),remove(),pop(),index(),count(),sort(),reverse(),copy(),clear(). - Most methods modify in-place and return None — never assign their result back to the variable.
-
list.sort()modifies in-place;sorted(list)returns a new sorted list. Both acceptreverse=Trueandkey=fn. -
Use
.copy()or[:]for a shallow copy — avoids unintended mutation through shared references. -
List comprehension:
[expr for x in iterable if condition]— faster and more Pythonic than equivalent loops for building lists.
append(x) adds the argument
as a single element to the end of the list — including adding a list as
a nested element.
extend(iterable) iterates over the argument
and adds each element individually to the end of the list — flattening the
iterable into the list.
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]] ← nested list added
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4] ← elements added individually
The sort() method modifies the list
in-place and returns None. If you
write my_list = my_list.sort(), Python first
sorts the list (correct), then assigns
None to
my_list — destroying the reference to your
sorted list. The same issue applies to
append(),
reverse(),
extend(), and
clear(). The fix is either to call without
assignment (my_list.sort()) or use
sorted() which returns a new list.
-
list.sort()— modifies the original list in-place, returnsNone. The original list is changed permanently. -
sorted(list)— returns a new sorted list, the original list is unchanged. Works on any iterable (not just lists).
a = [3,1,2]
b = sorted(a) # a unchanged, b = [1,2,3]
a.sort() # a is now [1,2,3], returns None
b = a does not copy the list — it
creates a second reference to the same list object in memory.
Modifying b also modifies
a because they point to the same data. This
is called aliasing.
To get an independent copy, use:
b = a.copy(),
b = a[:], or
b = list(a). For nested lists, use
import copy; b = copy.deepcopy(a).
words = ["hi", "Python", "is", "awesome", "cool", "go"]
result = [w.upper() for w in words if len(w) > 4]
print(result)
# ['PYTHON', 'AWESOME']
The condition if len(w) > 4 filters
first, then w.upper() transforms the passing
items.
["a","b","c","d","e"][1:4] return?
[x**2 for x in range(4) if x % 2 == 0]?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.