Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Python Lists: From Basics to Nested Lists

2 min read .
Python Lists: From Basics to Nested Lists

Python lists are mutable ordered collections and one of the most commonly used data structures in the language. They work well for sequences that need to grow, shrink, reorder, or contain arbitrary Python objects.

Create Lists

empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]

A list can contain values of different types, although homogeneous lists are often easier to process predictably.

Access and Slice Items

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

print(numbers[0])
print(numbers[-1])
print(numbers[1:4])

Slicing returns a new list.

Add Items

Append one item:

numbers.append(60)

Add all items from another iterable:

numbers.extend([70, 80])

Insert at a specific position:

numbers.insert(1, 15)

Repeated insertion near the front of a large list can be expensive because later elements need to be shifted.

Remove Items

Remove the first matching value:

numbers.remove(30)

Remove and return an item by index:

removed = numbers.pop(1)

Delete without returning the value:

del numbers[1]

Clear all items:

numbers.clear()

Update Items

numbers = [1, 2, 3]
numbers[1] = 20

Slice assignment can replace multiple items:

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

Loop Through a List

for number in numbers:
    print(number)

When you need the index as well:

for index, number in enumerate(numbers):
    print(index, number)

List Comprehensions

Build transformed or filtered lists concisely:

squares = [number * number for number in range(6)]
even_squares = [number * number for number in range(10) if number % 2 == 0]

Prefer an ordinary loop when the transformation has multiple steps or side effects.

Sorting

Sort a list in place:

numbers.sort()

Create a sorted copy:

sorted_numbers = sorted(numbers)

Sort complex objects with a key function:

users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
]

users.sort(key=lambda user: user["age"])

Nested Lists

Lists can model grids or nested data:

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

print(matrix[1][2])  # 6

Be careful when creating repeated nested lists. This creates shared inner objects:

rows = [[0] * 3] * 2

Prefer:

rows = [[0] * 3 for _ in range(2)]

so each row is a separate list.

Copying Lists

A shallow copy can be created with:

copy = numbers.copy()

For nested mutable objects, use copy.deepcopy() only when you genuinely need an independent recursive copy.

Conclusion

Lists are Python’s general-purpose mutable sequence. Learn indexing, slicing, mutation methods, comprehensions, sorting, and the behavior of nested mutable objects to use them safely and efficiently.

Related Posts

chevron-up