Lists: Beginner
TikTok serves over 1 billion users a personalized feed that is, at its core, a ranked list of video IDs rebuilt hundreds of times per day for each person. Python list operations like filtering candidate videos, sorting by predicted engagement score, and slicing the top results into a watchable sequence are the mechanics behind the scroll that keeps people watching for an average of 95 minutes daily. Every append, every slice, and every index lookup you learn here is a direct building block of systems operating at that scale. By the end of this lesson, you will have the foundational skills to create, access, and modify lists with confidence.
Creating Lists
Store multiple values in order
Empty Lists
The empty list prints as [] with nothing inside. The built-in len() function tells us how many items are in the list. An empty list has a length of 0.
Lists Hold Any Data Type
Checking List Length
The len() function is one of Python's most frequently used tools. When you pass a list to len(), it returns the number of items in that list. This is called the list's length or size. Knowing the length is essential for many operations, such as iterating through items or checking if a list is empty.
The fruits list has 5 items, so len(fruits) returns 5. In the second example, we check if the tasks list is empty before deciding what message to display. This is a common pattern in real programs where you need to handle the case of an empty list differently from a list with items.
Accessing Items by Index
Retrieve any item by its position
To access an item, write the list name followed by the index in square brackets. The expression fruits[0] means "give me the item at index 0 of the fruits list," which is "apple". The expression fruits[3] gives us "date", the item at index 3.
Visualizing Index Positions
A key relationship to remember: for a list with N items, the valid indices range from 0 to N-1. If a list has 4 items, the indices are 0, 1, 2, and 3. The last valid index is always the length minus one. This is why fruits[4] would cause an error for a 4-item list: index 4 does not exist.
Why Zero-Based Indexing?
Negative Indexing
Negative indexing is especially useful when you want the last item but do not know how long the list is. Instead of calculating len(colors) - 1, you can simply use colors[-1]. This makes your code cleaner and less error-prone.
- Counts from start (left)
- list[0] = first item
- list[3] = fourth item
- Counts from end (right)
- list[-1] = last item
- list[-3] = third from end
> A list of colors ["red", "green", "blue", "yellow"] is stored in a variable. Pick a positive or negative index to access a specific item.
colors = ["red", "green", "blue", "yellow"] print(colors[])
Invalid Index Behavior
0 <= index < len(list) for positive indices, or -len(list) <= index < 0 for negative indices.Modifying Items by Index
Adding Items to Lists
Grow your collections with new data
Lists would be far less useful if they could not grow. Python provides two primary methods for adding items: append() adds an item to the end, and insert() adds an item at a specific position. Understanding when to use each method is essential for writing efficient code.
append(): Adding to the End
The .append() method adds exactly one item to the end of a list. It is the most common way to add items because adding to the end is fast and does not require moving other items around. The syntax is list_name.append(item).
Each call to append() adds one item to the end of the list. The list grows from 2 items to 5 items. Notice that append() does not require you to specify where to add the item; it always goes at the end.
Building Lists with Loops
A common pattern in Python is to start with an empty list and use append() inside a loop to build it up. This is useful when you need to process data and collect results, or when the items you want to add depend on some calculation.
We start with an empty list called squares. The loop runs for numbers 1 through 5 (range(1, 6) includes 1 and excludes 6). For each number, we calculate its square and append the result. After the loop completes, squares contains all five squared values.
This example filters a list to keep only even numbers. The modulo operator % returns the remainder after division. If number % 2 equals 0, the number is even. We append only those even numbers to our new list.
insert(): Specific Position
The .insert() method lets you add an item at any position in the list, not just the end. It takes two arguments: the index where you want the new item, and the item itself. The syntax is list_name.insert(index, item).
Inserting at the Beginning
insert() Edge Cases
When the index exceeds the list length, Python simply adds the item at the end. This means insert(100, "z") on a 2-item list is equivalent to append("z"). Similarly, inserting at the exact length of the list adds to the end.
- Always adds to end
- Takes one argument
- Fast operation - O(1)
- Adds at specific position
- Takes two arguments
- Slower - O(n) due to shifting
The notation O(1) means the operation takes the same amount of time regardless of list size. O(n) means the time grows with the list size because items must be shifted. For large lists, preferring append() over insert() can significantly improve performance.
> Add multiple items from another list in one call. Pick the method that merges an entire iterable onto the end, and the built-in that counts the total elements afterward.
tasks = ["clean", "cook"] tasks.(["shop", "pack"]) print((tasks)) print(tasks[-1])
append() and extend() are the two most common ways to grow a list. Knowing which to use depends on whether you are adding a single item or merging a whole collection of items.
insert() is useful when position matters, but use it sparingly. Since it must shift every element after the insertion point, it becomes slower as the list grows longer.
All three methods modify the list in place and return None. If you try to assign the result of tasks.append("x") to a variable, you will get None, not the updated list.
Removing Items from Lists
Delete items by value or position
Just as you can add items to lists, you can remove them. Python provides several ways to remove items, each suited for different situations. The remove() method deletes by value, while pop() deletes by position. The del statement offers another approach. Understanding the differences helps you choose the right tool.
remove() - Delete by Value
The .remove() method finds and removes the first occurrence of a specific value. You tell Python what value to remove, and it searches the list to find it. The syntax is list_name.remove(value).
Notice that "eggs" appears twice in the original list. The remove() method only removes the first occurrence: the "eggs" at index 1. The second "eggs" (originally at index 3, now at index 2 after the first one is removed) remains in the list.
When Value Does Not Exist
The in operator checks if a value exists in a list and returns True or False. By checking first, we avoid the ValueError and can handle the "not found" case gracefully.
pop() - Remove by Position
The .pop() method removes an item at a specific index and returns that item. Unlike remove(), which works with values, pop() works with positions. If you call pop() without an argument, it removes and returns the last item.
The key difference from remove() is that pop() gives you back the removed item. This is useful when you need to use that item for something, like processing tasks from a to-do list. You remove the task and immediately have access to it.
pop() vs remove()
- Works with values
- Finds and removes first match
- Returns nothing (None)
- Raises ValueError if not found
- Works with indices
- Removes at exact position
- Returns the removed item
- Raises IndexError if bad index
Choose remove() when you know the value you want to remove but not necessarily its position. Choose pop() when you know the position, or when you need the last item. Use pop() without arguments when processing items from the end of a list, like emptying a stack.
The del Statement
Python also provides the del statement for removing items. Unlike pop(), del does not return the removed item. It simply deletes whatever you specify.
del removes the item at the specified index. After deleting index 2 (which was 30), the remaining items shift left. Then deleting index 0 (which was 10 after the shift) removes another item. Use del when you do not need the removed value.
del when you just want to delete. Both are O(n) for arbitrary indices because items must shift, but pop() without arguments is O(1) since removing the last item requires no shifting.Checking for Items with in
The in operator is one of Python's most readable features. It checks whether a value exists in a list and returns True or False. You can also use not in to check for absence. This is especially useful before calling remove() to avoid ValueError.
"banana" is in the list, so the first check returns True. "mango" is not in the list, so the second check returns False. The third expression uses not in and returns True because "mango" is indeed not in the list.
Using in with Conditionals
> Remove an item by its position and capture the removed value. Pick the method that deletes by index and returns the item, and the built-in that measures the remaining list size.
colors = ["red", "green", "blue"] removed = colors.(1) print(removed) print((colors))
pop() is especially useful when you need to process and remove items from a list one at a time, such as reading tasks off a to-do list or undoing actions in reverse order.
remove() searches through the list until it finds the first matching value. If the same value appears multiple times, only the first occurrence is removed. Call remove() in a loop to delete all occurrences.
del is the most flexible: it can remove a single item by index or a whole slice of items at once. Unlike pop(), it does not return the removed value, so use pop() when you need to use what you removed.
Safe List Access
Handle missing items without crashing
- IndexError from using an index equal to len(list) instead of len(list) - 1.
- TypeError from assigning the
Nonereturn of append() or sort() to a variable. - Unexpected mutations when two variables reference the same list object.
- Skipped items when removing elements from a list while iterating over it.
Off-by-One Errors
- list[len(list)] for last item
- list[1] for first item
- list[-1] or list[len(list)-1]
- list[0] for first item
Assigning append() Result
A very common mistake is writing new_list = old_list.append(item). The .append() method modifies the list in place and returns None. If you assign its result to a variable, that variable will be None, not the updated list.
Notice that result is None, but numbers was correctly modified. The fix is simple: do not assign the result of append(). Just call the method on its own.
> This code assigns the result of .append() back to the variable, but append() returns None. The list reference is overwritten and lost.
TypeError: NoneType - append() returns None, not the list
Modifying While Iterating
Lists Are References
Both variables show [1, 2, 3, 4] because they point to the same list. To create an independent copy, use the .copy() method or slice notation.
- Use list[-1] for last item
- Check "in" before remove()
- Use .copy() for independence
- Iterate over a copy to modify
- Use list[len(list)] for last item
- Call remove() without checking
- Assign alias = original as copy
- Remove items while iterating
> You are a data analyst at Fitbit building a Python script that collects daily step counts into a list, tracks a full week of readings, adds each new day's value, removes erroneous entries, and uses safe index access to retrieve specific days for anomaly flagging.
in to check if an item exists in the listOrganize multiple values in one place
- Category
- Python
- Difficulty
- beginner
- Duration
- 46 minutes
- Challenges
- 0 hands-on challenges
Topics covered: Creating Lists, Accessing Items by Index, Adding Items to Lists, Removing Items from Lists, Safe List Access
Lesson Sections
- Creating Lists (concepts: pyListCreate)
Every list in Python is defined using square brackets: [ and ]. These brackets tell Python that you are creating a list rather than some other type of data. Inside the brackets, you place the items you want to store, separated by commas. Each comma acts as a divider between individual items. In the first example, we create a list called numbers containing five integers. The square brackets wrap around all five values, and commas separate each value from the next. In the second example, we create
- Accessing Items by Index
Every item in a list has a position number called an index. Think of indices like addresses in an apartment building: each apartment has a specific number that lets you find it directly. Similarly, each list item has an index that lets you access it without looking through the entire list. The critical concept to understand is that Python uses zero-based indexing. This means the first item is at index 0, not index 1. The second item is at index 1, the third at index 2, and so on. This might feel
- Adding Items to Lists (concepts: pyListModify)
append(): Adding to the End Building Lists with Loops insert(): Specific Position When we insert "b" at index 1, the items "c" and "d" shift to the right to make room. What was at index 1 ("c") moves to index 2. What was at index 2 ("d") moves to index 3. The new item "b" takes position 1. Inserting at the Beginning To insert at the very beginning of a list, use index 0. This pushes all existing items one position to the right. Every existing item shifts right by one position. "second" moves fro
- Removing Items from Lists
remove() - Delete by Value When Value Does Not Exist If you try to remove a value that is not in the list, Python raises a ValueError. This error tells you that the value you asked to remove could not be found. To avoid this error, you should check whether the value exists before trying to remove it. This is a defensive programming technique that makes your code more robust. pop() - Remove by Position pop() vs remove() The del Statement Checking for Items with in Using in with Conditionals The i
- Safe List Access
Accessing list elements safely requires understanding how Python handles indices, references, and mutations. This section covers the patterns that prevent IndexError exceptions, unexpected None values, and accidental data corruption when working with lists. Before diving into specific pitfalls, here are the most frequent list-related errors that beginners encounter. Recognizing these patterns early will save you hours of debugging. Off-by-One Errors The most common indexing mistake is forgetting