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

Python Lists

A list is like a shopping list where items are kept in order. You can look at any item by its position, change it, or go through them all.
Syntax
python
list_name = [item1, item2, item3]
list_name[index]

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])  # first item, index 0
print(items[-1])  # last item, negative index counts from the end

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  # reassigns the element at index 1 in place
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:  # yields each value directly, not the index
    print(item)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using an index past the end, as in items[len(items)], which raises IndexError because the last valid index is len(items) - 1.
  2. Copying a list with b = a, which only creates a second name for the same list, so changing b also changes a; use a.copy() or a[:].
  3. Removing or adding items while looping over the same list, which skips elements because the indexes shift during iteration.

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.