Back to series
· 14 min read

Python Lists: Definition, Access, and Modification


I. What Is a List

A list is a built-in mutable sequence type provided by Python, used to store multiple pieces of data in a single variable.

A list has the following core characteristics:

  1. Ordered: elements are arranged in insertion order and can be accessed by index.
  2. Mutable: after a list is created, its elements can be modified, added, and deleted.
  3. Duplicates allowed: the same value can appear multiple times in a list.
  4. Type flexibility: the same list can store data of different types.
  5. Supports nesting: a list element can be another list or another container object.
  6. Dynamic length: elements can be added or removed as needed without specifying a fixed length in advance.

Example:

numbers = [10, 20, 30, 40]

print(numbers)
print(type(numbers))

Output:

[10, 20, 30, 40]
<class 'list'>

Lists are suitable for storing a set of data with sequential relationships, for example:

  • A list of user names.
  • A list of product prices.
  • A list of order records.
  • Student exam scores.
  • A collection of file paths.
  • Data records returned by an API.

1. Differences Between Lists and Other Containers

Common built-in containers in Python include lists, tuples, sets, and dictionaries.

Data Structure Ordered Mutable Allows Duplicates Main Use
list Yes Yes Yes Ordered data sequence
tuple Yes No Yes Fixed-structure data
set Order not guaranteed Yes No Collection of unique elements
dict Preserves insertion order Yes Keys cannot be duplicated Key-value mapping

The main difference between lists and tuples is mutability; the main difference between lists and sets is that lists preserve order and allow duplicate elements; the difference between lists and dictionaries is that lists access elements by positional index, while dictionaries access values by key.

II. Defining and Creating Lists

Python provides multiple ways to create lists, which can be chosen according to the data source and use case.

1. Creating a List with Square Brackets

The most common way is to use [].

numbers = [1, 2, 3, 4, 5]

names = ["Alice", "Bob", "Charlie"]

mixed = [100, "Python", True, 3.14, None]

print(numbers)
print(names)
print(mixed)

Elements in a list can be of different types; they are not required to all be the same.

2. Creating an Empty List

An empty list is a list that contains no elements.

list1 = []
list2 = list()

print(list1)
print(list2)

print(type(list1))
print(type(list2))

Output:

[]
[]
<class 'list'>
<class 'list'>

Both ways can create an empty list.

In actual development, using [] is usually recommended because the syntax is more concise.

3. Constructing a List Using list()

list() is Python's built-in type constructor that can convert an iterable into a list.

text = "Python"
numbers = range(1, 6)
values = (10, 20, 30)
unique = {1, 2, 3}

print(list(text))
print(list(numbers))
print(list(values))
print(list(unique))

Example output:

['P', 'y', 't', 'h', 'o', 'n']
[1, 2, 3, 4, 5]
[10, 20, 30]
[1, 2, 3]

Note that a set itself does not guarantee a fixed iteration order; therefore, when converting a set with list(), you should not rely on any particular element order.

4. Creating a Numeric List with range()

range() can generate a sequence of integers, which can then be converted to a list with list().

numbers = list(range(5))

print(numbers)

Output:

[0, 1, 2, 3, 4]

range() supports specifying a start value, an end value, and a step:

numbers = list(range(2, 11, 2))

print(numbers)

Output:

[2, 4, 6, 8, 10]

In range(start, stop, step):

  • start: the starting value, included in the result.
  • stop: the end boundary, not included in the result.
  • step: the step size, which defaults to 1.

5. Creating Lists with List Comprehensions

List comprehensions can quickly generate a new list from existing data.

squares = [number ** 2 for number in range(1, 6)]

print(squares)

Output:

[1, 4, 9, 16, 25]

You can also apply conditional filtering:

evens = [
    number
    for number in range(1, 11)
    if number % 2 == 0
]

print(evens)

Output:

[2, 4, 6, 8, 10]

List comprehensions are suited to simple data transformation and filtering. If the logic is complex, an ordinary for loop is usually clearer.

III. Accessing Lists by Index

Lists are a sequence type and support accessing elements by index.

An index indicates the position of an element in a sequence.

Python lists use zero-based indexing.

1. Forward Indexing

Forward indices increase from left to right:

fruits = ["apple", "banana", "orange", "grape"]

print(fruits[0])
print(fruits[1])
print(fruits[2])
print(fruits[3])

Output:

apple
banana
orange
grape

The correspondence between indices and element positions:

Index Element
0 apple
1 banana
2 orange
3 grape

The list contains 4 elements, so the valid forward index range is 0 to 3.

2. Reverse Indexing

Python lists support negative indices, accessing elements from right to left.

  • -1: the last element.
  • -2: the second-to-last element.
  • -3: the third-to-last element.
  • -4: the fourth-to-last element.

Example:

fruits = ["apple", "banana", "orange", "grape"]

print(fruits[-1])
print(fruits[-2])
print(fruits[-3])
print(fruits[-4])

Output:

grape
orange
banana
apple

The correspondence between forward and reverse indices:

Forward Index Reverse Index Element
0 -4 apple
1 -3 banana
2 -2 orange
3 -1 grape

Negative indices are very handy for accessing elements at the end of a list.

3. Index Out of Range

If you use an index outside the list's range, an IndexError is raised.

numbers = [10, 20, 30]

print(numbers[3])

The error message looks something like:

IndexError: list index out of range

Because the list has only three elements, the valid indices are 0, 1, and 2, and index 3 does not exist.

If you are not sure whether an index is valid, you can check the list length first:

numbers = [10, 20, 30]

index = 2

if 0 <= index < len(numbers):
    print(numbers[index])
else:
    print("索引超出范围")

You can also use exception handling:

numbers = [10, 20, 30]

try:
    print(numbers[5])
except IndexError:
    print("访问位置不存在")

Note that list indexing does not automatically return a default value. When an access is out of bounds, you should explicitly handle the exception or check the boundary in advance.

4. Using len() to Get the List Length

len() is used to get the number of elements in a list.

numbers = [10, 20, 30, 40, 50]

print(len(numbers))

Output:

5

You can use len() to get the position of the last element:

numbers = [10, 20, 30, 40, 50]

last_index = len(numbers) - 1

print(numbers[last_index])

However, using a negative index directly is usually more concise:

print(numbers[-1])

The length of an empty list is 0:

empty = []

print(len(empty))

Output:

0

IV. List Slicing

Slicing is used to extract a portion of elements from a list and generate a new list.

Slicing is an important operation for Python sequence types; lists, tuples, and strings all support slicing.

1. Basic Syntax

list[start:stop:step]

Parameter meanings:

  • start: Starting index, inclusive.
  • stop: Ending index, exclusive.
  • step: Step size, defaulting to 1.

Example:

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4])

Output:

[20, 30, 40]

The slice extracts the elements at indices 1, 2, and 3, and does not include index 4.

2. Omitting the Start Index

If start is omitted, it defaults to the beginning of the list.

numbers = [10, 20, 30, 40, 50]

print(numbers[:3])

Output:

[10, 20, 30]

3. Omitting the Stop Index

If stop is omitted, extraction continues to the end of the list by default.

numbers = [10, 20, 30, 40, 50]

print(numbers[2:])

Output:

[30, 40, 50]

4. Omitting Both Start and Stop Indices

numbers = [10, 20, 30, 40, 50]

print(numbers[:])

Output:

[10, 20, 30, 40, 50]

numbers[:] creates a new list containing all elements from the original list.

Note that this is only a shallow copy; it does not recursively copy nested objects inside the list.

5. Using a Step

The step controls the interval between extracted elements.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[::2])

Output:

[0, 2, 4, 6, 8]

A step of 2 means extracting every other element.

6. Reverse Slicing

If the step is negative, elements can be extracted from right to left.

numbers = [10, 20, 30, 40, 50]

print(numbers[::-1])

Output:

[50, 40, 30, 20, 10]

This approach can quickly generate a new list in reverse order.

Note that [::-1] does not modify the original list; it returns a new list.

7. Boundary Rules for Slicing

Slicing differs from direct indexing in an important way:

  • Direct indexing out of bounds usually raises IndexError.
  • If slice boundaries exceed the list range, it usually does not raise an exception; instead, it extracts elements according to the available range.

Example:

numbers = [10, 20, 30]

print(numbers[0:100])
print(numbers[10:20])

Output:

[10, 20, 30]
[]

This feature makes slicing more convenient when handling data of uncertain length.

8. Slice range diagram

Original list:

Index:     0    1    2    3    4    5
Element:   10   20   30   40   50   60

numbers[1:4]

Extracted:      20   30   40

9. Relationship between a slice and the original list

A slice creates a new list, but the element objects inside it are not deep-copied by default.

original = [10, 20, 30]

copied = original[:]

copied[0] = 100

print(original)
print(copied)

Output:

[10, 20, 30]
[100, 20, 30]

For ordinary immutable integers, modifying an element in the new list does not affect the original list.

However, if the elements themselves are mutable objects, you need to be aware of the shallow copy issue.

V. Modifying List Elements

A list is a mutable object, meaning its elements can be modified after creation.

1. Modifying elements by index

fruits = ["apple", "banana", "orange"]

fruits[1] = "grape"

print(fruits)

Output:

['apple', 'grape', 'orange']

By assigning through an index, you can directly replace the element at the specified position.

2. Modifying multiple elements

You can modify multiple elements at once through slice assignment.

numbers = [1, 2, 3, 4, 5]

numbers[1:4] = [20, 30, 40]

print(numbers)

Output:

[1, 20, 30, 40, 5]

Slice assignment can not only replace data with the same number of elements, but also change the length of the list.

numbers = [1, 2, 3, 4, 5]

numbers[1:3] = [20, 30, 40, 50]

print(numbers)

Output:

[1, 20, 30, 40, 50, 4, 5]

The original slice range contained two elements, and it is now replaced with four elements, so the list length increases.

3. Deleting elements using slices

Assigning an empty list to a slice can delete a range of elements.

numbers = [1, 2, 3, 4, 5]

numbers[1:4] = []

print(numbers)

Output:

[1, 5]

You can also use del:

numbers = [1, 2, 3, 4, 5]

del numbers[1:4]

print(numbers)

The output is the same:

[1, 5]

4. Using slices for stepped assignment

When a slice specifies a step other than 1, the number of elements in the assigned sequence must match the number of positions being replaced.

numbers = [1, 2, 3, 4, 5, 6]

numbers[::2] = [10, 30, 50]

print(numbers)

Output:

[10, 2, 30, 4, 50, 6]

If the number of elements does not match, a ValueError is raised.

numbers = [1, 2, 3, 4, 5, 6]

numbers[::2] = [10, 20]

The error message is similar to:

ValueError: attempt to assign sequence of size 2 to extended slice of size 3

VI. Adding Elements to a List

Python provides multiple methods for adding data to a list; the most commonly used are append(), extend(), and insert().

1. append(): Add one element at the end

append() is used to add one element to the end of a list.

Syntax:

list.append(element)

Example:

fruits = ["apple", "banana"]

fruits.append("orange")

print(fruits)

Output:

['apple', 'banana', 'orange']

append() adds only one object at a time.

If you add a list, that list is added to the original list as a single element:

numbers = [1, 2, 3]

numbers.append([4, 5])

print(numbers)

Output:

[1, 2, 3, [4, 5]]

At this point the list contains four elements, and the last element is itself a list.

2. extend(): add multiple elements at once

extend() is used to add the elements of an iterable to the end of a list one by one.

Syntax:

list.extend(iterable)

Example:

numbers = [1, 2, 3]

numbers.extend([4, 5, 6])

print(numbers)

Output:

[1, 2, 3, 4, 5, 6]

Unlike append(), extend() iterates over the argument and adds elements one by one.

numbers = [1, 2, 3]

numbers.append([4, 5])
print(numbers)

numbers = [1, 2, 3]

numbers.extend([4, 5])
print(numbers)

Output:

[1, 2, 3, [4, 5]]
[1, 2, 3, 4, 5]

3. insert(): insert an element at a specified position

insert() inserts an element at a specified position in the list.

Syntax:

list.insert(index, element)

Example:

fruits = ["apple", "orange"]

fruits.insert(1, "banana")

print(fruits)

Output:

['apple', 'banana', 'orange']

Elements after the insertion position are shifted to the right.

If the index is greater than the list length, the element is inserted at the end of the list; if the index is less than 0, it is adjusted according to the negative-index rules, and the final insertion position is restricted to near the beginning of the list.

4. Differences among the three adding methods

Method Purpose How it adds
append(x) Add one object Add as a whole to the end
extend(iterable) Add a group of elements Append one by one
insert(i, x) Add an object at a specified position Insert a single object

Execution flow:

flowchart TD
    A["Need to add data to the list"] --> B{"Which adding method to use?"}
    B -->|append| C["Add the object as a whole to the end"]
    B -->|extend| D["Iterate over the iterable"]
    B -->|insert| E["Locate the specified index"]
    D --> F["Append elements one by one"]
    E --> G["Insert the element and shift subsequent elements"]
    C --> H["Obtain the modified list"]
    F --> H
    G --> H

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

VII. Deleting elements from a list

Lists support several deletion methods, and you can choose different methods depending on the deletion target.

1. remove(): delete an element by value

remove() deletes the first element in the list that matches the specified value.

Syntax:

list.remove(value)

Example:

numbers = [10, 20, 30, 20, 40]

numbers.remove(20)

print(numbers)

Output:

[10, 30, 20, 40]

If the list contains multiple identical elements, remove() deletes only the first match.

If the specified value does not exist, a ValueError is raised.

You can check whether the element exists first:

numbers = [10, 20, 30]

if 40 in numbers:
    numbers.remove(40)
else:
    print("元素不存在")

2. pop(): Remove an element by index and return it

pop() removes the element at the specified position and returns the removed element.

Syntax:

list.pop(index)

If the index is omitted, the last element is removed by default.

numbers = [10, 20, 30, 40]

value = numbers.pop()

print(value)
print(numbers)

Output:

40
[10, 20, 30]

Specifying an index:

numbers = [10, 20, 30, 40]

value = numbers.pop(1)

print(value)
print(numbers)

Output:

20
[10, 30, 40]

If the index is out of range, an IndexError is raised.

For an empty list, calling pop() likewise raises an IndexError.

3. clear(): Empty the list

clear() removes all elements from the list but keeps the list object itself.

numbers = [10, 20, 30]

numbers.clear()

print(numbers)

Output:

[]

Unlike reassigning a new list, clear() modifies the original list object directly.

4. del: Delete an element or a slice

del is a Python statement, not a list method.

It can delete an element by index, and it can also delete multiple elements within a slice range.

numbers = [10, 20, 30, 40, 50]

del numbers[1]

print(numbers)

Output:

[10, 30, 40, 50]

Deleting a range of elements:

numbers = [10, 20, 30, 40, 50]

del numbers[1:4]

print(numbers)

Output:

[10, 50]

del can also delete a variable name:

numbers = [1, 2, 3]

del numbers

After execution, the name numbers in the current scope is deleted, and the original object can no longer be accessed through that name.

5. Comparison of deletion methods

Method Deletion basis Returns the removed element Characteristics
remove(x) Element value No Deletes the first matching value
pop(i) Index Yes Deletes and returns the element
clear() All elements No Empties the list
del Index or slice No A Python deletion statement

6. Common pitfalls when deleting elements

Do not delete the current element at will while iterating forward over a list.

For example:

numbers = [1, 2, 3, 4, 5, 6]

for number in numbers:
    if number % 2 == 0:
        numbers.remove(number)

print(numbers)

This approach may cause elements to be skipped, because after an element is deleted, the positions of the following elements shift while the iterator keeps moving according to its original traversal progress.

The following approaches are recommended instead.

Method 1: Create a new list.

numbers = [1, 2, 3, 4, 5, 6]

numbers = [
    number
    for number in numbers
    if number % 2 != 0
]

print(numbers)

Method 2: modify the list in place using slice assignment.

numbers = [1, 2, 3, 4, 5, 6]

numbers[:] = [
    number
    for number in numbers
    if number % 2 != 0
]

print(numbers)

The second approach preserves the identity of the original list object, so other references pointing to that list also observe the change.

VIII. Searching For and Checking List Elements

Lists provide several methods for determining whether an element exists, finding an element's position, and counting how many times an element occurs.

1. Using in to check whether an element exists

in is used to determine whether a specified element exists in a list.

fruits = ["apple", "banana", "orange"]

print("apple" in fruits)
print("grape" in fruits)

Output:

True
False

not in is used to determine whether an element does not exist:

fruits = ["apple", "banana", "orange"]

print("grape" not in fruits)

Output:

True

Checking list membership usually requires comparing elements one by one, giving a time complexity of O(n).

If you frequently need to check whether a large number of elements exist, consider using a set.

2. index(): find an element's index

index() returns the position where the specified value first appears.

Syntax:

list.index(value)

Example:

fruits = ["apple", "banana", "orange", "banana"]

position = fruits.index("banana")

print(position)

Output:

1

If the element does not exist, a ValueError is raised.

You can specify a search range:

numbers = [10, 20, 30, 20, 40]

print(numbers.index(20, 2))

Output:

3

Parameter meanings:

list.index(value, start, stop)

Here start and stop specify the search range, and stop is not included in the range.

3. count(): count element occurrences

count() counts how many times a certain value appears in the list.

numbers = [1, 2, 2, 3, 2, 4, 5]

print(numbers.count(2))

Output:

3

If the element does not exist, it returns 0:

print(numbers.count(100))

Output:

0

4. Comparing the checking, searching and counting methods

Operation Method Return value
Check whether it exists value in list True / False
Check whether it does not exist value not in list True / False
Find an element's position list.index(value) Index
Count occurrences list.count(value) Integer

IX. Sorting and Reversing Lists

Python provides two common ways to sort: sort() and sorted().

1. sort(): sort in place

sort() modifies the original list directly and does not return the sorted list.

numbers = [5, 2, 8, 1, 9]

numbers.sort()

print(numbers)

Output:

[1, 2, 5, 8, 9]

By default, it sorts in ascending order.

2. Descending Sort

You can achieve descending order with reverse=True.

numbers = [5, 2, 8, 1, 9]

numbers.sort(reverse=True)

print(numbers)

Output:

[9, 8, 5, 2, 1]

3. sorted(): Returns a New List

sorted() is a built-in function, not a list method.

It returns a new sorted result without modifying the original list.

numbers = [5, 2, 8, 1, 9]

result = sorted(numbers)

print(result)
print(numbers)

Output:

[1, 2, 5, 8, 9]
[5, 2, 8, 1, 9]

4. Using key to Specify Sorting Rules

You can specify the sorting criterion with the key parameter.

words = ["banana", "apple", "watermelon", "pear"]

words.sort(key=len)

print(words)

Output:

['pear', 'apple', 'banana', 'watermelon']

Here it sorts in ascending order based on string length.

You can also sort by a field in a dictionary:

students = [
    {"name": "Alice", "score": 88},
    {"name": "Bob", "score": 95},
    {"name": "Charlie", "score": 76},
]

students.sort(
    key=lambda student: student["score"],
    reverse=True
)

print(students)

The sorting result is arranged from highest to lowest score.

5. reverse(): In-place Reversal

reverse() directly reverses the order of elements in the list.

numbers = [1, 2, 3, 4, 5]

numbers.reverse()

print(numbers)

Output:

[5, 4, 3, 2, 1]

reverse() is not a sorting operation; it only changes the direction of the existing elements.

6. Reversing with Slicing

numbers = [1, 2, 3, 4, 5]

result = numbers[::-1]

print(result)
print(numbers)

Output:

[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]

Slicing creates a new list, and the original list remains unchanged.

7. Comparison of Sorting and Reversal Methods

Method Modifies Original List Returns New List Main Purpose
sort() Yes No, returns None In-place sorting
sorted() No Yes Returns sorted result
reverse() Yes No, returns None In-place reversal
[::-1] No Yes Generates a reversed list

Keep in mind: sort() and reverse() are both in-place modification methods; you should not use their return values as new lists.

Incorrect example:

numbers = [3, 1, 2]

result = numbers.sort()

print(result)

Output:

None

Correct usage:

numbers = [3, 1, 2]

numbers.sort()

print(numbers)

X. Copying Lists

Lists are mutable objects, so special attention must be paid to reference relationships when copying lists.

1. Direct assignment is not copying

list1 = [1, 2, 3]

list2 = list1

list2.append(4)

print(list1)
print(list2)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4]

The reason is that list1 and list2 point to the same list object.

Executing:

list2 = list1

does not create a new list; it merely makes both variables reference the same object.

2. Using copy() for a shallow copy

copy() can create a new list object.

list1 = [1, 2, 3]

list2 = list1.copy()

list2.append(4)

print(list1)
print(list2)

Output:

[1, 2, 3]
[1, 2, 3, 4]

The two lists are now different objects.

You can also use slicing:

list2 = list1[:]

Or use the constructor:

list2 = list(list1)

For lists, these methods are all shallow copies.

3. What is a shallow copy

A shallow copy (Shallow Copy) only copies the outermost container and does not recursively copy nested objects inside.

Example:

original = [
    [1, 2],
    [3, 4]
]

copied = original.copy()

copied[0][0] = 100

print(original)
print(copied)

Output:

[[100, 2], [3, 4]]
[[100, 2], [3, 4]]

Why does modifying copied affect original?

Because although the two lists are different outer objects, their nested lists are still the same set of objects.

Structural relationship:

original ──┐
           ├── first element in the outer list ──> [1, 2]
copied ────┘

original ──┐
           ├── second element in the outer list ──> [3, 4]
copied ────┘

4. Using deepcopy() for a deep copy

If you need to recursively copy nested objects, you can use copy.deepcopy().

import copy

original = [
    [1, 2],
    [3, 4]
]

copied = copy.deepcopy(original)

copied[0][0] = 100

print(original)
print(copied)

Output:

[[1, 2], [3, 4]]
[[100, 2], [3, 4]]

A deep copy recursively copies the relevant objects in the object structure, making the mutable nested objects in the new and old structures independent of each other.

However, for data structures containing file handles, locks, network connections, or complex custom objects, a deep copy may not be suitable and may not always succeed.

5. Comparison of the three assignment and copy methods

Operation Creates a new list Copies nested objects inside
list2 = list1 No No
list1.copy() Yes No
copy.deepcopy(list1) Yes Usually recursively copied

11. Nested structure of lists

Lists can contain other lists, forming two-dimensional or even multidimensional structures.

1. Creating a two-dimensional list

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix)

A two-dimensional list can be understood as a list composed of multiple one-dimensional lists.

2. Accessing elements of a two-dimensional list

Accessing a two-dimensional list requires two levels of indexing.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])
print(matrix[0][1])
print(matrix[1][2])