← Back to Python Course | Chapter 6: Data Structures | Lesson 1 of 12

Python Lists

What is a List?

A list stores an ordered sequence of items that can be changed after creation, and unlike arrays in many other languages it can freely mix types (numbers, strings, even other lists) in the same list. It's the default general-purpose container you reach for in Python.

Example: What is a List?

python
mixed = [1, "two", 3.0, [4]]
print(mixed)

Accessing List Items

Square-bracket indexing starts at 0 for the first element, and negative indices count backward from the end so my_list[-1] always gives you the last item without needing to know the list's length.

Example: Accessing List Items

python
items = [10, 20, 30]
print(items[0])
print(items[-1])

List Slicing

Slicing with list[start:end] pulls out a sub-list without modifying the original, and because the end index is exclusive, list[0:3] gives exactly three elements -- a detail that trips up beginners coming from languages with inclusive ranges.

Example: List Slicing

python
items = [10, 20, 30, 40, 50]
print(items[0:3])

Modifying List Items

Because lists are mutable, you can reassign my_list[i] = new_value to change an element in place without creating a new list object, which matters for performance and also means two variables pointing at the same list will both see the change.

Example: Modifying List Items

python
items = [10, 20, 30]
items[1] = 99
print(items)

Iterating over Lists

A for loop over a list yields each element directly in order (not the index), which is the idiomatic way to process items -- reach for enumerate() only when you also need the position of each item.

Example: Iterating over Lists

python
items = [10, 20, 30]
for item in items:
    print(item)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.