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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a list in Python?
Q2:What is zero-based indexing?
Q3:How does negative indexing work?
Q4:What is the difference between indexing and slicing?
Q5:What does it mean that lists are mutable?
Q6:What is the difference between list length and the last valid positive index?
Q7:What is IndexError, and when can it occur with a list?
Q8:What is the difference between a list slice and direct indexing beyond the list boundary?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: