Skip to content
PythonWorking with Collectionsbeginner18 min read

Lists: Creating and Indexing

Learn to create lists, access items using positive and negative indexes, slice sequences, and update list elements.

In this lesson, you will learn

  • ✓Explain what a Python list is and why lists are ordered and mutable.
  • ✓Create lists containing numbers, strings, and mixed data types.
  • ✓Access list elements using zero-based positive and negative indexes.
  • ✓Use slicing to retrieve a portion of a list.
  • ✓Modify list elements and determine the length of a list.
  • ✓Recognize IndexError and handle empty lists safely.
  • ✓Trace list operations and predict their exact output.

1. What Is a List?

A list is an ordered, mutable sequence of items. Ordered means the items have a defined position. Mutable means you can change the contents of an existing list after creating it.

Lists are written using square brackets, with items separated by commas. A list can contain integers, floating-point numbers, strings, Boolean values, or even other lists.

You can store a list in a variable and use that variable to access or modify its elements. Instead of creating a separate variable for every value, you can group related values in one list.

A list can contain duplicate values, and its items do not all need to have the same data type. However, lists are easiest to work with when their contents have a clear purpose.

Create a list of numbers

Create a list of numbers
python
numbers = [10, 20, 30, 40]
print(numbers)
Output
[10, 20, 30, 40]

The square brackets create a list containing four integers. The variable numbers refers to the list. print(numbers) displays the list using square brackets and comma-separated values.

Note

An empty list is valid. It has no elements, but you can add elements to it later using list methods, which will be covered in a later lesson.

2. Positive Indexing: Access Items by Position

Each element in a Python list has an index, which identifies its position. Python uses zero-based indexing, meaning the first element has index 0, the second has index 1, and the third has index 2.

To access an item, write the list variable followed by the index inside square brackets. For example, numbers[0] accesses the first item in numbers.

For a non-empty list with n elements, the valid positive indexes range from 0 to n - 1. The final index is one less than the list's length.

Remember that an index is a position, not the value stored at that position. A list may contain the value 100 at index 0, for example, but the index is still 0.

Access individual list elements

Access individual list elements
python
colors = ["red", "green", "blue"]
 
print(colors[0])
print(colors[1])
print(colors[2])
Output
red green blue

colors[0] accesses the first item, "red". colors[1] accesses the second item, "green". colors[2] accesses the third item, "blue". The list contains three items, so its valid positive indexes are 0, 1, and 2.

Note

For a list containing four elements, the indexes are 0, 1, 2, and 3—not 1, 2, 3, and 4.

3. Negative Indexing: Access Items from the End

Python also supports negative indexes. Negative indexing counts positions backward from the end of a list.

The index -1 refers to the last element, -2 refers to the second-to-last element, and -3 refers to the third-to-last element.

For a list of length n, valid negative indexes range from -n to -1. Negative indexing is useful when you need the last few elements without calculating their positive indexes.

Positive and negative indexes access the same list elements; they simply count positions in opposite directions.

Access the last items

Access the last items
python
colors = ["red", "green", "blue"]
 
print(colors[-1])
print(colors[-2])
print(colors[-3])
Output
blue green red

colors[-1] accesses the last item, "blue". colors[-2] accesses the second-to-last item, "green". colors[-3] accesses the first item, "red". Negative indexing counts backward, but it does not change the order of the list.

4. List Slicing: Retrieve a Portion of a List

Indexing retrieves one element, while slicing retrieves a sequence of elements. The basic slicing syntax is list[start:stop].

The start index is included, but the stop index is excluded. For example, numbers[1:3] returns the elements at indexes 1 and 2.

You can omit the start index to begin at the start of the list, or omit the stop index to continue to the end. You can also provide a third value, called the step, using list[start:stop:step].

Slicing produces a new list. A slice does not change the original list merely by being evaluated.

Select a range of elements

Select a range of elements
python
numbers = [10, 20, 30, 40, 50]
 
print(numbers[1:4])
Output
[20, 30, 40]

The start index 1 is included, so the slice begins with 20. The stop index 4 is excluded, so the element 50 at index 4 is not included. The slice contains the elements at indexes 1, 2, and 3.

Note

The stop index is excluded in ordinary slicing. This makes the number of selected elements easy to determine when the step is 1: for a valid non-negative slice boundary, the length is the difference between stop and start, subject to the list's actual boundaries.

5. Lists Are Mutable: Change an Element

A list is mutable, which means its contents can be changed after the list is created. You can replace an element by assigning a new value to a valid index.

The syntax is list[index] = new_value. Python replaces the element at that position; it does not insert a new element or automatically shift the other elements.

You can also use len(list) to find the number of elements in a list. The length is a count, while the last positive index is one less than that count for a non-empty list.

Modify an existing element

Modify an existing element
python
colors = ["red", "green", "blue"]
colors[1] = "yellow"
 
print(colors)
Output
["red", "yellow", "blue"]

Initially, the item at index 1 is "green". The assignment colors[1] = "yellow" replaces that element. The list still contains three elements, in the same positions, but the second value has changed.

Note

The length of a list is not the same as its last index. A list with four elements has length 4 and last positive index 3. An empty list has length 0 and no valid indexes.

6. Trace List Operations and Handle Edge Cases

When tracing list code, track both the current contents of the list and the index used by each expression. If an element is modified, record the updated list before evaluating later statements.

Accessing an index that does not exist raises IndexError. For example, a list with three elements has valid positive indexes 0, 1, and 2. Accessing index 3 is invalid.

An empty list has no elements, so neither empty_list[0] nor empty_list[-1] is valid. Before accessing an element, check that the list contains enough items for the requested index.

Slicing behaves differently from direct indexing at the boundaries. A slice such as numbers[1:100] does not raise IndexError merely because its stop index exceeds the list length; it returns the available elements from the specified start onward.

Trace a list modification

Trace a list modification
python
numbers = [5, 10, 15]
print(numbers[1])
 
numbers[1] = 20
print(numbers)
print(numbers[-1])
Output
10 [5, 20, 15] 15

Initially, numbers contains 5, 10, and 15. The first print accesses index 1 and displays 10. The assignment replaces the value at index 1 with 20, so the list becomes [5, 20, 15]. The final print accesses index -1, which refers to the last element, 15.

Caution

Direct indexing with a nonexistent position raises IndexError. If a list might be empty or shorter than expected, check its length or use an appropriate iteration or validation approach before accessing an element.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming the first list element has index 1.

Why it happens: Python sequences use zero-based indexing, so the first element is at index 0.

Incorrect Approach
script.py
python
Assuming the first list element has index 1.
Correct Solution
script.py
python
Python uses zero-based indexing. The first element is at index 0, the second at index 1, and the third at index 2.

Key takeaway: Python uses zero-based indexing. The first element is at index 0, the second at index 1, and the third at index 2.

#2 Using an index equal to the list's length.

Why it happens: A list of length n has valid positive indexes from 0 through n-1; index n is out of range.

Incorrect Approach
script.py
python
Using an index equal to the list's length.
Correct Solution
script.py
python
For a non-empty list of length n, the last positive index is n - 1. Index n is outside the valid range.

Key takeaway: For a non-empty list of length n, the last positive index is n - 1. Index n is outside the valid range.

#3 Confusing negative indexes with negative list values.

Why it happens: A negative index specifies a position counted from the end, not a negative value stored in the list.

Incorrect Approach
script.py
python
Confusing negative indexes with negative list values.
Correct Solution
script.py
python
A negative index specifies a position counted from the end. For example, numbers[-1] selects the last element even if that element is a positive number.

Key takeaway: A negative index specifies a position counted from the end. For example, numbers[-1] selects the last element even if that element is a positive number.

#4 Expecting the stop index of a slice to be included.

Why it happens: A slice's stop boundary is exclusive, so the element at the stop index is not included.

Incorrect Approach
script.py
python
Expecting the stop index of a slice to be included.
Correct Solution
script.py
python
The start index is included, but the stop index is excluded. Use numbers[1:4] to select indexes 1, 2, and 3.

Key takeaway: The start index is included, but the stop index is excluded. Use numbers[1:4] to select indexes 1, 2, and 3.

#5 Assuming a slice changes the original list.

Why it happens: A normal slice creates a new list and does not mutate the original list.

Incorrect Approach
script.py
python
Assuming a slice changes the original list.
Correct Solution
script.py
python
A normal slice creates a new list. Assigning to a list index, by contrast, modifies the existing list.

Key takeaway: A normal slice creates a new list. Assigning to a list index, by contrast, modifies the existing list.

#6 Confusing the list length with the last index.

Why it happens: Length counts elements, while the final valid positive index is one less than the length for a non-empty list.

Incorrect Approach
script.py
python
Confusing the list length with the last index.
Correct Solution
script.py
python
len(numbers) counts the elements. For a non-empty list, the last positive index is len(numbers) - 1.

Key takeaway: len(numbers) counts the elements. For a non-empty list, the last positive index is len(numbers) - 1.

#7 Accessing an element of an empty list.

Why it happens: An empty list has no first element, so direct access at index 0 raises IndexError.

Incorrect Approach
script.py
python
Accessing an element of an empty list.
Correct Solution
script.py
python
An empty list has no valid positive or negative element indexes. Check whether the list contains an element before accessing one.

Key takeaway: An empty list has no valid positive or negative element indexes. Check whether the list contains an element before accessing one.

#8 Expecting an invalid slice boundary to behave like invalid direct indexing.

Why it happens: Slice boundaries are clipped to sequence bounds in many cases, while direct indexing beyond the valid range raises IndexError.

Incorrect Approach
script.py
python
Expecting an invalid slice boundary to behave like invalid direct indexing.
Correct Solution
script.py
python
A slice such as numbers[1:100] returns the available elements and does not raise IndexError just because the stop boundary is beyond the list. Directly accessing numbers[100] is different and raises IndexError.

Key takeaway: A slice such as numbers[1:100] returns the available elements and does not raise IndexError just because the stop boundary is beyond the list. Directly accessing numbers[100] is different and raises IndexError.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a list in Python?
Answer:
A list is an ordered, mutable sequence that can store multiple items. It is created using square brackets, and its elements can be accessed by index.
Q2:What is zero-based indexing?
Answer:
Zero-based indexing means the first element has index 0, the second has index 1, and so on. For a non-empty list of length n, the last valid positive index is n - 1.
Q3:How does negative indexing work?
Answer:
Negative indexes count backward from the end of a sequence. Index -1 accesses the last element, -2 accesses the second-to-last element, and so on.
Q4:What is the difference between indexing and slicing?
Answer:
Indexing accesses a single element, such as numbers[1]. Slicing retrieves a sequence of elements, such as numbers[1:4]. The start of a slice is included, while the stop is excluded.
Q5:What does it mean that lists are mutable?
Answer:
Mutable means a list can be changed after creation. For example, numbers[0] = 100 replaces the first element of the existing list with 100.
Q6:What is the difference between list length and the last valid positive index?
Answer:
The length counts the number of elements, while the last valid positive index is one less than the length for a non-empty list. For example, a four-element list has length 4 and last positive index 3.
Q7:What is IndexError, and when can it occur with a list?
Answer:
IndexError is raised when direct indexing requests a position outside the valid indexes of a list. For example, accessing numbers[3] in a three-element list raises IndexError because its valid positive indexes are 0, 1, and 2.
Q8:What is the difference between a list slice and direct indexing beyond the list boundary?
Answer:
Directly accessing a nonexistent index, such as numbers[10], raises IndexError. A slice such as numbers[1:10] returns the available elements from the specified start to the end without raising IndexError merely because the stop boundary exceeds the list length.

Key takeaways

  • A list is an ordered, mutable sequence created using square brackets.
  • Lists can contain different data types and duplicate values.
  • Positive indexing starts at 0, and negative indexing starts at -1 from the end.
  • For a non-empty list of length n, the last valid positive index is n - 1.
  • Slicing retrieves a portion of a list and excludes the stop index.
  • A normal slice creates a new list rather than changing the original list.
  • Lists are mutable, so you can replace an element using list[index] = value.
  • len(list) returns the number of elements, not the last index.
  • Direct indexing outside the valid range raises IndexError, including when indexing an empty list.
  • Tracing indexes and list contents step by step helps prevent indexing and slicing mistakes.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: