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

Daily Life
Interviews

Store multiple values in order

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.
1# Creating a list of numbers
2numbers = [10, 20, 30, 40, 50]
3print(numbers)
4
5# Creating a list of names
6students = ["Alice", "Bob", "Charlie"]
7print(students)
>>>Output
[10, 20, 30, 40, 50]
['Alice', 'Bob', 'Charlie']
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 a list of three strings. Notice that when Python prints strings, it shows them with quotes to indicate they are text rather than numbers.

Empty Lists

Sometimes you need to create a list that starts with no items. This is called an empty list. You might do this when you plan to add items later, perhaps based on user input or calculations. Creating an empty list is simple: use square brackets with nothing between them.
1shopping_cart = []
2print(shopping_cart)
3print(len(shopping_cart))
>>>Output
[]
0

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

Unlike some programming languages that require all items in a collection to be the same type, Python lists can hold any combination of data types. You can mix integers, floating-point numbers, strings, boolean values, and even other lists in the same list. This flexibility makes Python lists extremely powerful.
1# A list mixing different data types
2mixed = [42, "hello", 3.14, True, None]
3print(mixed)
4
5# A user profile with different types of information
6user_profile = ["Maya Chen", 28, "Software Engineer", True, 75000.50]
7print(user_profile)
>>>Output
[42, 'hello', 3.14, True, None]
['Maya Chen', 28, 'Software Engineer', True, 75000.5]
The first list contains an integer (42), a string ("hello"), a floating-point number (3.14), a boolean (True), and a special value called None that represents the absence of data. The second list represents information about a person: name, age, job title, employment status, and salary.
TIP
While Python allows mixed types in lists, keeping all items the same type often makes your code easier to understand and process. Use mixed-type lists when you have a specific reason, like storing different attributes of a single entity.

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.

1fruits = ["apple", "banana", "cherry", "date", "elderberry"]
2print(len(fruits))
3
4# Common pattern: check if a list is empty
5tasks = []
6if len(tasks) == 0:
7 print("No tasks to complete!")
8else:
9 print("You have tasks to do")
>>>Output
5
No tasks to complete!

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

Daily Life
Interviews

Retrieve any item by its position

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 counterintuitive at first, but it is standard across most programming languages and becomes natural with practice.
1fruits = ["apple", "banana", "cherry", "date"]
2
3# Access individual items by their index
4print(fruits[0])
5print(fruits[1])
6print(fruits[2])
7print(fruits[3])
>>>Output
apple
banana
cherry
date

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

Let us visualize how indices map to positions in the list ["apple", "banana", "cherry", "date"]:
[0][1][2][3]
[0]
First: "apple"
Indexing starts at zero
[1]
Next: "banana"
One position from start
[2]
Third: "cherry"
Two positions from start
[3]
Fourth: "date"
Last valid index is N-1

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?

Zero-based indexing might seem strange if you are used to counting "first, second, third" in everyday life. However, there are good reasons most programming languages use it. The index represents an offset from the beginning of the list. The first item is zero positions away from the start, so its index is 0. The second item is one position away, so its index is 1.
This system also makes arithmetic with indices cleaner. If you have a list of 10 items, the indices are 0 through 9. If you want to split the list in half, items 0-4 are the first half and items 5-9 are the second half. The math works out evenly without special cases.

Negative Indexing

Python offers a convenient feature for accessing items from the end of a list: negative indexing. When you use a negative number as an index, Python counts backward from the end. Index -1 is the last item, -2 is the second-to-last, and so on.
1colors = ["red", "green", "blue", "yellow", "purple"]
2
3print(colors[-1])
4print(colors[-2])
5print(colors[-5])
>>>Output
purple
yellow
red

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.

Positive Index
  • Counts from start (left)
  • list[0] = first item
  • list[3] = fourth item
Negative Index
  • Counts from end (right)
  • list[-1] = last item
  • list[-3] = third from end
Try accessing different items from this list by choosing between positive and negative indices. Run each combination to see what Python returns.
Fill in the Blank

> 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

If you try to access an index that does not exist, Python raises an IndexError. This is Python's way of telling you that you asked for something that is not there. Understanding this error is important because it is one of the most common mistakes when working with lists.
1fruits = ["apple", "banana", "cherry"]
2
3# This will cause an error!
4# IndexError: list index out of range
5print(fruits[10])
The fruits list has only 3 items (indices 0, 1, and 2). Asking for index 10 is asking for an item that does not exist. Python stops execution and displays "IndexError: list index out of range." This error tells you exactly what went wrong: you tried to use an index outside the valid range.
TIP
Before accessing an index, verify it is valid. Check that 0 <= index < len(list) for positive indices, or -len(list) <= index < 0 for negative indices.

Modifying Items by Index

Lists are mutable, meaning you can change their contents after creation. To modify an item, use the index on the left side of an assignment statement. This replaces the old value with a new one at that position.
1planets = ["Mercury", "Venus", "Mars", "Jupiter"]
2print("Before:", planets)
3
4# Fix: Earth should be at index 2
5planets[2] = "Earth"
6print("After:", planets)
7
8# Update the first planet
9planets[0] = "MERCURY"
10print("Final:", planets)
>>>Output
Before: ['Mercury', 'Venus', 'Mars', 'Jupiter']
After: ['Mercury', 'Venus', 'Earth', 'Jupiter']
Final: ['MERCURY', 'Venus', 'Earth', 'Jupiter']
In the first modification, we replaced "Mars" at index 2 with "Earth". In the second, we changed "Mercury" to uppercase. The list itself is modified; we are not creating a new list. This is what "mutable" means: the original object changes.

Adding Items to Lists

Daily Life
Interviews

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).

1shopping = ["milk", "bread"]
2print("Before:", shopping)
3
4shopping.append("eggs")
5print("After first append:", shopping)
6
7shopping.append("cheese")
8print("After second append:", shopping)
9
10shopping.append("butter")
11print("Final:", shopping)
>>>Output
Before: ['milk', 'bread']
After first append: ['milk', 'bread', 'eggs']
After second append: ['milk', 'bread', 'eggs', 'cheese']
Final: ['milk', 'bread', 'eggs', 'cheese', 'butter']

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.

append() adds to the end
append() adds to the end
New items always go after the last existing item in the list.
Returns None, not the list
Returns None, not the list
append() modifies the list in place. Do not assign its result.
Called on the list object
Called on the list object
Use dot notation: my_list.append(item), not append(my_list).

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.

1squares = []
2
3for num in range(1, 6):
4 squared = num * num
5 squares.append(squared)
6
7print(squares)
>>>Output
[1, 4, 9, 16, 25]

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.

1source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2evens = []
3
4for number in source:
5 if number % 2 == 0:
6 evens.append(number)
7
8print(evens)
>>>Output
[2, 4, 6, 8, 10]

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).

1letters = ["a", "c", "d"]
2print("Before:", letters)
3
4# Insert "b" at index 1
5letters.insert(1, "b")
6print("After insert at 1:", letters)
>>>Output
Before: ['a', 'c', 'd']
After insert at 1: ['a', 'b', 'c', 'd']
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.
1queue = ["second", "third", "fourth"]
2print("Before:", queue)
3
4# Insert at the beginning
5queue.insert(0, "first")
6print("After:", queue)
>>>Output
Before: ['second', 'third', 'fourth']
After: ['first', 'second', 'third', 'fourth']
Every existing item shifts right by one position. "second" moves from index 0 to index 1, "third" from 1 to 2, and "fourth" from 2 to 3. The new item "first" takes index 0.

insert() Edge Cases

What happens if you try to insert at an index beyond the list's current length? Python handles this gracefully by inserting at the end.
1small_list = ["a", "b"]
2print("Before:", small_list)
3
4# Insert beyond list length
5small_list.insert(100, "z")
6print("After:", small_list)
7
8# This is equivalent to append
9small_list.insert(len(small_list), "end")
10print("After insert at length:", small_list)
>>>Output
Before: ['a', 'b']
After: ['a', 'b', 'z']
After insert at length: ['a', 'b', 'z', 'end']

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.

append()
  • Always adds to end
  • Takes one argument
  • Fast operation - O(1)
insert()
  • 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.

TIP
Use append() when you just need to add items to a list. Use insert() only when the specific position matters. If you find yourself frequently inserting at the beginning, consider whether a different data structure might be more efficient.
Python Quiz

> 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
insert
len
extend
sum

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

Daily Life
Interviews

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).

1groceries = ["milk", "eggs", "bread", "eggs", "cheese"]
2print("Before:", groceries)
3
4groceries.remove("eggs")
5print("After removing eggs:", groceries)
>>>Output
Before: ['milk', 'eggs', 'bread', 'eggs', 'cheese']
After removing eggs: ['milk', 'bread', 'eggs', 'cheese']

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

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.
1fruits = ["apple", "banana", "cherry"]
2
3# This will cause an error!
4# ValueError: list.remove(x): x not in list
5fruits.remove("mango")
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.
1fruits = ["apple", "banana", "cherry"]
2item_to_remove = "mango"
3
4if item_to_remove in fruits:
5 fruits.remove(item_to_remove)
6 print(f"Removed {item_to_remove}")
7else:
8 print(f"{item_to_remove} not found in list")
9
10print("Final list:", fruits)
>>>Output
mango not found in list
Final list: ['apple', 'banana', 'cherry']

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.

1stack = ["first", "second", "third", "fourth"]
2print("Before:", stack)
3
4# Pop without argument removes last item
5last = stack.pop()
6print("Popped:", last)
7print("After pop():", stack)
8
9# Pop with index removes specific item
10middle = stack.pop(1)
11print("Popped index 1:", middle)
12print("Final:", stack)
>>>Output
Before: ['first', 'second', 'third', 'fourth']
Popped: fourth
After pop(): ['first', 'second', 'third']
Popped index 1: second
Final: ['first', 'third']

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()

remove()
  • Works with values
  • Finds and removes first match
  • Returns nothing (None)
  • Raises ValueError if not found
pop()
  • 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.

1numbers = [10, 20, 30, 40, 50]
2print("Before:", numbers)
3
4del numbers[2]
5print("After del [2]:", numbers)
6
7del numbers[0]
8print("After del [0]:", numbers)
>>>Output
Before: [10, 20, 30, 40, 50]
After del [2]: [10, 20, 40, 50]
After del [0]: [20, 40, 50]

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.

TIP
Use pop() when you need the removed value. Use 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.

1fruits = ["apple", "banana", "cherry", "date"]
2
3# Check if items exist
4print("banana" in fruits)
5print("mango" in fruits)
6print("mango" not in fruits)
>>>Output
True
False
True

"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

The in operator is commonly used in if statements to control program flow based on whether an item exists:
1allowed_users = ["alice", "bob", "charlie"]
2username = "bob"
3
4if username in allowed_users:
5 print(f"Welcome, {username}!")
6else:
7 print("Access denied")
8
9# Check multiple conditions
10if username in allowed_users and len(username) > 2:
11 print(f"{username} is valid and long enough")
>>>Output
Welcome, bob!
bob is valid and long enough
This pattern is fundamental in real applications. You might check if a user is in an allowed list before granting access, or verify that a product exists in inventory before processing an order.
Python Quiz

> 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))
remove
clear
type
len
pop

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

Daily Life
Interviews

Handle missing items without crashing

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.
Most Common List Errors
  • IndexError from using an index equal to len(list) instead of len(list) - 1.
  • TypeError from assigning the None return 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

The most common indexing mistake is forgetting that indices start at 0. If you want the first item, use index 0, not 1. If you want the last item of a 5-item list, use index 4 or -1, not 5.
Wrong
  • list[len(list)] for last item
  • list[1] for first item
Correct
  • 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.

1numbers = [1, 2, 3]
2result = numbers.append(4)
3print("result:", result)
4print("numbers:", numbers)
>>>Output
result: None
numbers: [1, 2, 3, 4]

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.

1numbers = [1, 2, 3]
2numbers.append(4)
3print("numbers:", numbers)
>>>Output
numbers: [1, 2, 3, 4]
This bug appears constantly in beginner code. Try fixing it yourself by removing the extra tile that captures the None return value.
Debug Challenge

> 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

Removing items from a list while looping over it causes unexpected behavior. As items are removed, the indices shift, causing the loop to skip items.
1# WRONG - modifying
2numbers = [1, 2, 3, 4, 5]
3for num in numbers:
4 if num % 2 == 0:
5 numbers.remove(num)
The correct approach is to iterate over a copy of the list, or build a new list with only the items you want to keep.
1# CORRECT - iterate over a copy
2numbers = [1, 2, 3, 4, 5]
3# [:] creates a copy
4for num in numbers[:]:
5 if num % 2 == 0:
6 numbers.remove(num)
7print(numbers)
8
9# ALTERNATIVE - build a new list
10numbers = [1, 2, 3, 4, 5]
11odds_only = [num for num in numbers if num % 2 != 0]
12print(odds_only)
>>>Output
[1, 3, 5]
[1, 3, 5]

Lists Are References

When you assign a list to a new variable, you are not copying the list. Both variables point to the same list in memory. Changing one affects the other.
1original = [1, 2, 3]
2# NOT a copy, just another reference
3copy = original
4
5copy.append(4)
6
7print("original:", original)
8print("copy:", copy)
9print("Same object?", original is copy)
>>>Output
original: [1, 2, 3, 4]
copy: [1, 2, 3, 4]
Same object? True

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.

1original = [1, 2, 3]
2actual_copy = original.copy()
3
4actual_copy.append(4)
5
6print("original:", original)
7print("actual_copy:", actual_copy)
8print("Same object?", original is actual_copy)
>>>Output
original: [1, 2, 3]
actual_copy: [1, 2, 3, 4]
Same object? False
Here is a summary of the safe patterns you should adopt and the dangerous habits you should avoid when working with lists.
Do
  • Use list[-1] for last item
  • Check "in" before remove()
  • Use .copy() for independence
  • Iterate over a copy to modify
Don't
  • Use list[len(list)] for last item
  • Call remove() without checking
  • Assign alias = original as copy
  • Remove items while iterating
01
Create
Use square brackets [] to define a list with items separated by commas
02
Access
Use zero-based indexing list[0] or negative indexing list[-1] from the end
03
Grow
Use append() to add to end or insert() to place at a specific position
04
Shrink
Use remove() by value, pop() by index, or del to delete items
05
Guard
Always check bounds with len() and membership with the in operator
Lists are one of the most versatile and frequently used data structures in Python. Put these fundamentals to the test with hands-on challenges in the Python Builder.
PUTTING IT ALL TOGETHER

> 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.

[] list creation stores all seven days of step counts in order, making each day accessible by its position index.
Indexing with [] retrieves a specific day's count, like yesterday's steps, for direct comparison against the weekly average.
.append() adds each new day's reading to the end of the existing list without overwriting any prior recorded values.
Safe list access with len() and bounds checks prevents an IndexError when fewer than seven days of data have been collected.
KEY TAKEAWAYS
Lists are created with square brackets: [item1, item2, item3]
Indexing starts at 0; use list[0] for the first item
Negative indices count from end: list[-1] is the last item
.append(item) adds to the end (fast, O(1))
.insert(index, item) adds at a specific position (slower, O(n))
.remove(value) deletes the first occurrence of a value
.pop() removes and returns last item; .pop(i) for specific index
Use in to check if an item exists in the list
Assignment creates a reference, not a copy; use .copy() for independence

Organize 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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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