So far, we’ve stored individual values in variables. But what if you want to store multiple names, numbers, or other values together?
Creating a separate variable for every value would quickly become difficult to manage.
That’s where lists come in.
What Are Lists?
A list lets you store multiple items in a single variable.
Lists have a few important properties:
- Ordered: Items keep their position in the list.
- Mutable: You can change a list after creating it.
- Allow duplicates: The same value can appear more than once.
- Flexible: A list can contain different data types.
Let’s see how to create one.
Creating Lists
Lists are created using square brackets [], with items separated by commas.
# List of integers
numbers = [1, 2, 36, 3, 15]
# List of strings
colors = ["Red", "Yellow", "Blue"]
# List of mixed data types
mixed = [1, "John", 12, 5.3]
print(numbers)
print(colors)
print(mixed)
# Output:
# [1, 2, 36, 3, 15]
# ['Red', 'Yellow', 'Blue']
# [1, 'John', 12, 5.3]You can also create an empty list:
fruits = []You can add items to it later as you learn more list methods.
Finding the Length of a List
Remember the len() function from our string lesson? It works with lists, too.
It returns the number of items in a list.
numbers = [1, 2, 36, 3, 15]
length_of_list = len(numbers)
print(length_of_list)
# Output:
# 5There are five items in this list, so len(numbers) returns 5.
Accessing List Items
Every item in a list has a position called an index.
Python starts counting from 0, not 1.
For example:
fruits = ["Orange", "Apple", "Banana"]
# Indexes: 0 1 2
print(fruits[0])
print(fruits[1])
print(fruits[2])
# Output:
# Orange
# Apple
# BananaThe first item is at index 0, the second at index 1, and the third at index 2.
Negative Indexing
You can also access items from the end of a list using negative indexes.
-1refers to the last item.-2refers to the second-to-last item.-3refers to the third-to-last item.
For example:
fruits = ["Orange", "Apple", "Banana"]
# Negative indexes: -3 -2 -1
print(fruits[-1])
print(fruits[-2])
print(fruits[-3])
# Output:
# Banana
# Apple
# OrangeNegative indexing is useful when you want to access an item from the end without calculating its position.
One thing to remember: If you try to access an index that doesn’t exist, Python raises an IndexError.
Checking Whether an Item Exists
You can use the in keyword to check whether a value exists in a list.
For example:
fruits = ["Orange", "Apple", "Banana"]
if "Orange" in fruits:
print("Orange is in the list.")
else:
print("Orange is not in the list.")
# Output:
# Orange is in the list.Let’s try another example:
numbers = [1, 57, 13]
if 7 in numbers:
print("7 is in the list.")
else:
print("7 is not in the list.")
# Output:
# 7 is not in the list.You can also use not in to check whether an item is absent.
fruits = ["Orange", "Apple", "Banana"]
print("Mango" not in fruits)
# Output:
# TrueThis is helpful when you want to check whether a value is present before working with it.
What Is List Slicing?
Slicing lets you extract a portion of a list.
The syntax is:
list_name[start:end:step]Here’s what each part means:
start: The index where slicing begins.end: The index where slicing stops. This index is not included in the result.step: How many positions to move each time. This part is optional.
Let’s look at some examples.
Selecting a Range of Items
Suppose we have this list:
numbers = [1, 57, 13, 6, 18, 54]We can select items using positive indexes:
print(numbers[2:5])
# Output:
# [13, 6, 18]The slice starts at index 2 and stops before index 5.
Remember, the ending index is excluded, so the item at index 5 isn’t included.
You can also use negative indexes:
print(numbers[-5:-2])
# Output:
# [57, 13, 6]Here, slicing starts at index -5 and stops before index -2.
Slicing From a Given Index to the End
If you leave out the end index, Python includes the remaining items until the end of the list.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[2:])
# Output:
# [13, 6, 18, 54]You can also use a negative starting index:
print(numbers[-5:])
# Output:
# [57, 13, 6, 18, 54]Slicing From the Beginning
If you leave out the start index, Python begins with the first item.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[:4])
# Output:
# [1, 57, 13, 6]This includes items up to, but not including, index 4.
You can use a negative ending index, too:
print(numbers[:-2])
# Output:
# [1, 57, 13, 6]This excludes the last two items.
Skipping Items With a Step
The step value lets you skip items while slicing.
For example, numbers[::2] selects every second item, starting from index 0.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[::2])
# Output:
# [1, 13, 18]The selected items are at indexes 0, 2, and 4.
You can also start from a negative index:
print(numbers[-2::2])
# Output:
# [18]Here, slicing starts at index -2, which contains 18. Since the step is positive, Python moves forward through the list. There are no more items after 18, so that’s the only item returned.
If you use a negative step, it moves backward through the list. So, in the below example [::-1] gives a reversed copy.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[::-1])
# Output:
# [54, 18, 6, 13, 57, 1]Slices Make a New List
Slicing never changes the original list. It creates a new one.
numbers = [1, 57, 13, 6]
part = numbers[1:3]
print(part)
print(numbers)
# Output:
# [57, 13]
# [1, 57, 13, 6]Quick Reminder
When slicing a list, remember:
- The
startindex is included. - The
endindex is excluded. - You can leave out the
startorendindex. - The
stepcontrols how many positions Python skips. - Slicing creats a new list.
Unlike accessing a single item with an invalid index, slicing beyond the list’s boundaries never raise an IndexError. Python simply returns the available items.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[2:100])
# Output:
# [13, 6, 18, 54]What Is List Comprehension?
Imagine you have a list of names and want to create another list containing only names that meet a particular condition.
You could use a for loop and an if statement. But Python also lets you do this in a single expression using a list comprehension.
The basic syntax is:
[expression for item in iterable if condition]Here’s what each part means:
expression: The value or result to add to the new list. You can keep the original item or transform it.item: The current item being processed.iterable: The collection you’re going through.condition: An optional check that determines whether an item should be included.
Let’s understand this with examples.
Filtering Items From a List
Suppose we have a list of names and want to select only those containing the letter "a".
names = ["John", "Mark", "Bruno", "Dany"]
names_with_a = [
item for item in names if "a" in item
]
print(names_with_a)
# Output:
# ['Mark', 'Dany']Here’s how it works:
for item in namesgoes through each name.if "a" in itemchecks whether the name contains the letter"a".itemadds the matching name to the new list.
The result contains only "Mark" and "Dany".
Notice that the check is case-sensitive. A lowercase "a" doesn’t match an uppercase "A".
Transforming Items With List Comprehension
List comprehensions aren’t just for filtering. You can also transform each item before adding it to the new list.
For example, let’s create a list of squares from a list of numbers.
numbers = [1, 2, 3, 4, 5, 6]
squares = [n ** 2 for n in numbers]
print(squares)
# Output:
# [1, 4, 9, 16, 25, 36]Here’s what happens:
for n in numbersgoes through each number.n ** 2calculates its square.- The result is added to the new list.
Unlike our earlier example, we’re not filtering any items. We’re transforming every number into its square.
Transforming and Filtering Together
You can also transform items and filter them in the same list comprehension.
For example, let’s create squares of only the even numbers.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [
n ** 2 for n in numbers if n % 2 == 0
]
print(even_squares)
# Output:
# [4, 16, 36]Here’s how it works:
n % 2 == 0checks whether a number is even.- Only even numbers pass the condition.
n ** 2calculates the square of each number that passes.- The result contains the squares of
2,4, and6.
Using List Comprehension With Strings
Remember how we learned to loop through strings in our earlier string lesson?
A string is also an iterable, which means you can go through its characters one by one.
For example, let’s convert each character in "python" to uppercase.
letters = [letter.upper() for letter in "python"]
print(letters)
# Output:
# ['P', 'Y', 'T', 'H', 'O', 'N']Here’s what happens:
- Python goes through each character in
"python". letter.upper()converts each character to uppercase.- Each converted character is added to the new list.
You can also use range() to generate numbers.
numbers = [n for n in range(5)]
print(numbers)
# Output:
# [0, 1, 2, 3, 4]This creates a list containing numbers from 0 to 4.
Using if/else in List Comprehensions
So far, we’ve used if to decide whether an item should be included in the new list.
But what if you want to include every item while changing its value based on a condition?
You can use if/else inside the expression.
For example:
numbers = [3, -1, 4, -5]
cleaned = [n if n > 0 else 0 for n in numbers]
print(cleaned)
# Output:
# [3, 0, 4, 0]Here’s how it works:
- If
n > 0, the original number is included. - Otherwise,
0is included instead. - Every number produces a result, so the new list has the same number of items as the original.
Remember this difference:
- A filtering
ifgoes at the end because it decides whether to include an item. - An
if/elsegoes at the beginning as part of the expression because it decides which value to include.
Compare these two examples:
# Filtering: keep only even numbers
evens = [n for n in numbers if n % 2 == 0]
# Transforming: replace negative numbers with 0
cleaned = [n if n > 0 else 0 for n in numbers]The first example removes items that don’t match the condition. The second keeps every item but may change its value.
How Would You Do This With a Loop?
A list comprehension is a shorter alternative to a regular for loop.
For example, here’s how to create a list of names shorter than four characters using a loop:
names = ["John", "Mark", "Bruno", "Dany", "Jay"]
short_names = []
for name in names:
if len(name) < 4:
short_names.append(name)
print(short_names)
# Output:
# ['Jay']The loop checks each name and adds matching names to short_names.
append() adds an item to the end of a list.
Check list methods for detailed explanation of the append() method.
Now, here’s the same logic using a list comprehension:
names = ["John", "Mark", "Bruno", "Dany", "Jay"]
short_names = [
name for name in names if len(name) < 4
]
print(short_names)
# Output:
# ['Jay']Both approaches produce the same result.
The loop may be easier to understand when you’re starting out. As you become more comfortable with Python, list comprehensions can help you write concise code.
One thing to remember: Don’t make a list comprehension so complicated that it’s difficult to read. A regular loop is often better for more complex logic.
List Methods
Python provides following methods to manipulate lists.
Sorting a List with sort()
Python’s sort() method sorts a list in ascending order by default.
For numbers, that means smallest to largest. For strings, it sorts them alphabetically based on their character values.
numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers)
# Output:
# [1, 2, 3, 5, 8]Notice that we called sort() directly on the list. It changes the original list instead of creating a new one.
You can also sort a list in descending order by setting reverse=True.
numbers = [5, 2, 8, 1, 3]
numbers.sort(reverse=True)
print(numbers)
# Output:
# [8, 5, 3, 2, 1]Sorting Strings
You can use sort() with a list of strings, too.
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
# Output:
# ['apple', 'banana', 'cherry']One thing to remember: Python sorts strings based on character values, not just how words appear in a dictionary.
For example:
fruits = ["banana", "apple", "Cherry"]
fruits.sort()
print(fruits)
# Output:
# ['Cherry', 'apple', 'banana']Why does "Cherry" come first? Uppercase letters sort before lowercase letters in this comparison.
You can fix this using key=str.lower, which tells Python to compare the strings as lowercase. We’ll explore the key parameter in more detail when we learn how to pass functions as arguments.
fruits = ["banana", "apple", "Cherry"]
fruits.sort(key=str.lower)
print(fruits)
# Output:
# ['apple', 'banana', 'Cherry']A quick note: Sorting is stable. This means that when two items have the same sorting value, Python keeps their original relative order.
Also, avoid sorting a list that mixes numbers and strings, like [1, "a"]. Python cannot directly compare these values, so sorting raises a TypeError.
Important: sort() Returns None
This is a common mistake when working with lists.
numbers = [3, 1, 2]
numbers = numbers.sort()
print(numbers)
# Output:
# NoneWhat happened?
sort() changes the original list in place and returns None. When you assign its result back to numbers, you replace your list with None.
This is similar to what we learned about functions that don’t explicitly return a value.
So, use sort() on its own when you want to change the existing list:
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
# Output:
# [1, 2, 3]What If you want a new sorted list?
Use Python’s built-in sorted() function.
Unlike sort(), sorted() creates a new sorted list and leaves the original unchanged.
numbers = [3, 1, 2]
new_numbers = sorted(numbers)
print(new_numbers)
print(numbers)
# Output:
# [1, 2, 3]
# [3, 1, 2]You can also use sorted() with other iterables, including tuples and strings.
print(sorted((3, 1, 2)))
print(sorted("python"))
# Output:
# [1, 2, 3]
# ['h', 'n', 'o', 'p', 't', 'y']Remember the difference:
sort()changes the original list and returnsNone.sorted()returns a new sorted list and leaves the original unchanged.
Reversing a List with reverse()
The reverse() method reverses the current order of items in a list.
It doesn’t sort the items. It simply puts the last item first, the second-last item second, and so on.
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
# Output:
# [5, 4, 3, 2, 1]Just like sort(), reverse() changes the original list and returns None.
numbers = [1, 2, 3]
result = numbers.reverse()
print(result)
# Output:
# NoneIf you want a reversed copy without changing the original list, you can use the slicing technique.
numbers = [1, 2, 3, 4, 5]
reversed_numbers = numbers[::-1]
print(reversed_numbers)
print(numbers)
# Output:
# [5, 4, 3, 2, 1]
# [1, 2, 3, 4, 5]You can also sort a list in descending order with sort(reverse=True). That’s different from reverse(), which only flips the current order.
Finding an Item with index()
The index() method returns the index of the first occurrence of a value in a list.
Remember, Python indexing starts at 0.
fruits = ["apple", "banana", "cherry"]
position = fruits.index("banana")
print(position)
# Output:
# 1Here, "banana" is at index 1, so that’s what index() returns.
What if the item doesn’t exist?
If the value isn’t in the list, index() raises a ValueError.
fruits = ["apple", "banana", "cherry"]
print(fruits.index("grape"))
# ValueError: 'grape' is not in listTo avoid this error, you can use the in operator to check whether the item exists before searching for its index.
fruits = ["apple", "banana", "cherry"]
if "grape" in fruits:
print(fruits.index("grape"))
else:
print("Fruit not found")
# Output:
# Fruit not foundThis way, you only call index() when the item is present.
One more thing: if a value appears multiple times, index() returns only the first matching position.
numbers = [2, 4, 2, 6, 2]
print(numbers.index(2))
# Output:
# 0The first 2 is at index 0, so that’s the result. Even though 2 appears again at indices 2 and 4, index() doesn’t return those positions.
Counting Items with count()
The count() method tells you how many times a particular value appears in a list.
numbers = [1, 2, 3, 2, 4, 2, 5]
print(numbers.count(2))
# Output:
# 3The number 2 appears three times, so count() returns 3.
If the value doesn’t exist in the list, count() returns 0. It doesn’t raise an error.
fruits = ["apple", "banana", "cherry"]
print(fruits.count("grape"))
# Output:
# 0You can also count strings:
names = ["Sam", "Alex", "Sam", "John", "Sam"]
print(names.count("Sam"))
# Output:
# 3Adding Items with append()
The append() method adds one item to the end of a list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
# Output:
# ['apple', 'banana', 'cherry']You can add numbers, strings, or other types of values.
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
# Output:
# [1, 2, 3, 4]One important thing to remember: append() adds its argument as a single item. If you pass another list, it adds that entire list as one nested item.
fruits = ["apple", "banana"]
fruits.append(["grapes", "mango"])
print(fruits)
# Output:
# ['apple', 'banana', ['grapes', 'mango']]We’ll see how to add multiple items individually in the next section.
A common mistake
Like sort(), append() changes the existing list and returns None.
So, don’t assign its result back to the list.
fruits = ["apple", "banana"]
fruits = fruits.append("cherry")
print(fruits)
# Output:
# NoneInstead, call append() directly:
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
# Output:
# ['apple', 'banana', 'cherry']The same rule applies to insert() and extend(), which we’ll cover next. All three methods modify the original list and return None.
Adding Items at a Specific Position with insert()
What if you don’t want to add an item at the end?
That’s where insert() comes in. It adds an item at a position you choose.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits)
# Output:
# ['apple', 'banana', 'cherry']Here, 1 is the index where we want to add "banana".
Remember, list indexing starts at 0.
You can also use insert(0, item) to add an item at the beginning of a list.
numbers = [2, 3, 4]
numbers.insert(0, 1)
print(numbers)
# Output:
# [1, 2, 3, 4]What happens if you use an index that’s beyond the end of the list? Python adds the item at the end.
numbers = [1, 2, 3]
numbers.insert(100, 4)
print(numbers)
# Output:
# [1, 2, 3, 4]Adding Multiple Items with extend()
The extend() method adds items from another iterable to the end of a list.
An iterable is something Python can go through one item at a time, such as a list or a string.
Let’s start with another list.
fruits = ["apple", "banana"]
more_fruits = ["cherry", "grapes"]
fruits.extend(more_fruits)
print(fruits)
# Output:
# ['apple', 'banana', 'cherry', 'grapes']Notice the difference between append() and extend():
append()adds its argument as one item.extend()adds the items from an iterable individually.
Strings work with extend(), too
Remember how we looped through strings? Strings are iterable, so extend() can add their characters individually.
letters = ["a", "b"]
letters.extend("hi")
print(letters)
# Output:
# ['a', 'b', 'h', 'i']Each character is added as a separate item.
Just like append() and insert(), extend() modifies the original list and returns None.
Combining Lists with +
You can also combine two lists using the + operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)
# Output:
# [1, 2, 3, 4, 5, 6]Unlike append() and extend(), the + operator creates a new list. It doesn’t change either of the original lists.
fruits = ["apple", "banana"]
more_fruits = ["cherry", "grapes"]
combined = fruits + more_fruits
print(combined)
print(fruits)
# Output:
# ['apple', 'banana', 'cherry', 'grapes']
# ['apple', 'banana']One thing to remember: both sides of + must be lists when you’re using it to concatenate lists.
fruits = ["apple", "banana"]
print(fruits + "cherry")
# TypeError: can only concatenate list (not "str") to listIf you want to add one string to the end of a list, use append() instead.
What about +=?
You may also see += used with lists.
It adds items from the right-hand iterable to the existing list, much like extend().
numbers = [1, 2, 3]
numbers += [4, 5]
print(numbers)
# Output:
# [1, 2, 3, 4, 5]For lists, numbers += [4, 5] is similar to numbers.extend([4, 5]).
Copying a List with copy()
The copy() method creates a copy of a list.
But why do we need it?
Let’s look at what happens when we assign one list variable to another.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
# Output:
# [1, 2, 3, 4]
# [1, 2, 3, 4]You might expect a to remain [1, 2, 3]. But both variables show the same list.
That’s because b = a does not copy the list. Both names refer to the same list, so a change through one name is visible through the other.
You can check this using the is operator.
a = [1, 2, 3]
b = a
print(a is b)
# Output:
# Trueis checks whether two names refer to the same object. Here, they do.
Making an actual copy
To create a separate list, use copy().
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)
# Output:
# [1, 2, 3]
# [1, 2, 3, 4]Now, adding an item to b doesn’t change a.
You can also check the difference using is.
a = [1, 2, 3]
print(a is a.copy())
# Output:
# FalseThe copied list contains the same values, but it’s a different list object.
You can also create a copy of a list using [:].
a = [1, 2, 3]
b = a[:]
print(b)
# Output:
# [1, 2, 3]Both a.copy() and a[:] create a shallow copy of the list.
One important detail about shallow copies
A shallow copy creates a new outer list, but it doesn’t independently copy objects inside nested lists.
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
print(a)
# Output:
# [[1, 2, 99], [3, 4]]Why did a change, even though we copied it?
The outer lists are different, but the inner lists are shared. So, changing an inner list through b also affects what you see through a.
You don’t need to worry about deep copying yet. Just remember that copy() creates a separate outer list, not a completely independent copy of everything inside it.
Changing Items Using Their Index
We can access list items using their index.
We can use the same index to change an item.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)
# Output:
# ['apple', 'mango', 'cherry']Here, index 1 refers to "banana". We replaced it with "mango".
You can also use negative indexing to change an item from the end of the list.
fruits = ["apple", "banana", "cherry"]
fruits[-1] = "grapes"
print(fruits)
# Output:
# ['apple', 'banana', 'grapes']If you try to update an index that doesn’t exist, Python raises an IndexError.
fruits = ["apple", "banana"]
fruits[5] = "mango"
# IndexError: list assignment index out of rangeMake sure the index exists before assigning a new value.
Replacing multiple items with slice assignment
You can also change a range of items using slice assignment.
numbers = [10, 20, 30, 40, 50]
numbers[1:3] = [99]
print(numbers)
# Output:
# [10, 99, 40, 50]Here, numbers[1:3] selects 20 and 30. We replace those two items with 99.
Notice that the list becomes shorter because we replaced two items with one.
Removing an Item with remove()
The remove() method removes the first occurrence of a specific value from a list.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
# Output:
# ['apple', 'cherry']You don’t need to know the item’s index. Just pass the value you want to remove.
What if the value appears more than once?
numbers = [1, 2, 3, 2, 4]
numbers.remove(2)
print(numbers)
# Output:
# [1, 3, 2, 4]Only the first 2 was removed. The second one remains in the list.
What if the item doesn’t exist?
If the value isn’t in the list, remove() raises a ValueError.
fruits = ["apple", "banana", "cherry"]
fruits.remove("grapes")
# ValueError: list.remove(x): x not in listYou can avoid this error by checking whether the item exists first using in.
fruits = ["apple", "banana", "cherry"]
if "grapes" in fruits:
fruits.remove("grapes")
else:
print("Fruit not found")
# Output:
# Fruit not foundOne important detail: remove() returns None
Like sort(), remove() changes the existing list and returns None.
fruits = ["apple", "banana"]
result = fruits.remove("apple")
print(result)
print(fruits)
# Output:
# None
# ['banana']The item is removed, but the method doesn’t return the removed value.
If you need the removed value, use pop() instead.
How do you remove every matching item?
As we’ve seen, remove() removes only the first match. What if you want to remove all occurrences of a value?
You can use list comprehension.
numbers = [1, 2, 3, 2, 4]
numbers = [n for n in numbers if n != 2]
print(numbers)
# Output:
# [1, 3, 4]This creates a new list containing only the numbers that aren’t equal to 2.
We assign the new list back to numbers so the variable now refers to the filtered list.
Removing an Item with pop()
The pop() method removes an item by its index and returns the removed value.
If you don’t provide an index, it removes the last item.
fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop()
print(removed_fruit)
print(fruits)
# Output:
# cherry
# ['apple', 'banana']You can also provide an index to remove a specific item.
fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop(1)
print(removed_fruit)
print(fruits)
# Output:
# banana
# ['apple', 'cherry']Unlike remove(), pop() returns the removed item, so you can store it in a variable and use it later.
Remember:
-
remove(value)removes the first matching value. -
pop(index)removes and returns the item at an index. -
pop()without an index removes and returns the last item.
If you use an invalid index with pop(), Python raises an IndexError. Calling pop() on an empty list also raises an error:
fruits = []
fruits.pop()
# IndexError: pop from empty listRemoving Items with del
Python also has the del statement, which can delete a list item using its index.
fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits)
# Output:
# ['apple', 'cherry']You can use negative indexing, too.
fruits = ["apple", "banana", "cherry"]
del fruits[-1]
print(fruits)
# Output:
# ['apple', 'banana']You can even delete a range of items using slicing.
numbers = [10, 20, 30, 40, 50]
del numbers[1:4]
print(numbers)
# Output:
# [10, 50]Here, del numbers[1:4] removes the items at indices 1, 2, and 3. Remember that the ending index in a slice is not included.
You can also use del to delete the entire list variable.
fruits = ["apple", "banana"]
del fruits
print(fruits)
# NameError: name 'fruits' is not definedAfter deleting the variable, you can no longer use that name unless you assign a value to it again.
One small detail: del is a statement, not a method. You write del fruits[1] directly, without parentheses.
Removing All Items with clear()
What if you want to empty a list but keep the list variable?
Use clear().
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
# Output:
# []The list still exists, but it contains no items.
clear() vs assigning an empty list
These two operations might look similar, but they behave differently when another variable refers to the same list.
Let’s look at clear() first.
a = [1, 2]
b = a
a.clear()
print(b)
# Output:
# []Remember from earlier example that b = a doesn’t create a copy. Both names refer to the same list.
When we call a.clear(), we empty that shared list, so b also refers to an empty list.
Now let’s try assigning an empty list instead.
a = [1, 2]
b = a
a = []
print(a)
print(b)
# Output:
# []
# [1, 2]This time, a = [] makes a refer to a new empty list. It doesn’t empty the original list that b still refers to.
The difference:
a.clear()empties the existing list.a = []makes a refer to a new empty list.
Looping Through Lists
Now, let's learn how to go through a list one item at a time using loops.
Looping Through a List with for
Imagine you have a list of 100 names and want to print every name. Writing 100 separate print() statements would take a lot of time.
Instead, you can use a for loop.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherryLet’s understand what’s happening:
fruitsis the list we want to go through.fruitis a variable that holds the current item during each iteration.print(fruit)displays that item.
Python takes each item from the list, one at a time, and runs the code inside the loop.
You can name the loop variable whatever you like. Using a meaningful name makes your code easier to read.
names = ["Alex", "Sam", "Jordan"]
for name in names:
print(f"Hello, {name}!")
# Output:
# Hello, Alex!
# Hello, Sam!
# Hello, Jordan!Performing calculations with list items
You can also perform calculations while looping through a list.
numbers = [10, 20, 30]
for number in numbers:
print(number * 2)
# Output:
# 20
# 40
# 60Each number is multiplied by 2 before being printed.
Using if inside a list loop
You can use an if statement inside a loop to perform an action only when a condition is true.
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
print(number)
# Output:
# 2
# 4
# 6The condition checks whether each number is divisible by 2. Only even numbers are printed.
Looping Through a List with while
You can also use a while loop to go through a list. This time, we’ll use an index to access each item.
fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
# Output:
# apple
# banana
# cherryLet’s break it down:
- We start with
index = 0because list indexing begins at0. while index < len(fruits)keeps the loop running as long as the index is within the list.fruits[index]accesses the item at the current position.index += 1moves to the next position.
We use len(fruits) to check how many items are in the list. Once index reaches that length, the condition becomes false and the loop stops.
Important: Don’t forget to increase the index. Otherwise, the loop may continue forever because its condition never becomes false.
For most simple list operations, a for loop is easier to read. A while loop is useful when you need more control over when the loop continues or stops.
Getting Both the Index and Item with enumerate()
Sometimes, you need more than the item itself. You might also want to know its position in the list.
For example, imagine printing a numbered list of tasks.
Python provides enumerate() to help with this.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherryDuring each iteration, enumerate() gives you two values:
index: the position of the item.fruit: the item itself.
Python assigns those values to the two variables in the loop.
Starting the count from 1
By default, enumerate() starts counting from 0, just like list indexing.
But if you want a numbered list that starts at 1, pass start=1.
fruits = ["apple", "banana", "cherry"]
for number, fruit in enumerate(fruits, start=1):
print(f"{number}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. cherryThis is useful for menus, numbered tasks, and lists that people need to read.
Remember: start=1 changes the numbers produced by enumerate(). It doesn’t change the actual indexes of the list.
Updating List Items While Looping
Sometimes, you want to change the items in a list while going through it.
But there’s something important to understand first.
Reassigning the loop variable doesn’t change the list
Look at this example:
numbers = [1, 2, 3]
for number in numbers:
number = number + 10
print(numbers)
# Output:
# [1, 2, 3]You might expect the list to become [11, 12, 13], but it remains unchanged.
Why?
number is just a variable that holds the current value during each iteration. Reassigning it doesn’t update the corresponding item in the original list.
If you want to create a new list with each number increased by 10, list comprehension is often the simpler option.
numbers = [1, 2, 3]
new_numbers = [n + 10 for n in numbers]
print(new_numbers)
print(numbers)
# Output:
# [11, 12, 13]
# [1, 2, 3]This creates a new list and leaves the original unchanged.
Updating the original list with enumerate()
If you want to update the existing list, you can use enumerate() to access each item’s index.
numbers = [1, 2, 3, 4]
for index, number in enumerate(numbers):
numbers[index] = number + 10
print(numbers)
# Output:
# [11, 12, 13, 14]Here, numbers[index] = number + 10 replaces the item at the current position.
This works because lists are mutable.
A Common Mistake: Removing Items While Looping
Here’s a mistake that’s easy to make when working with lists.
Imagine you want to remove every occurrence of 2 from a list.
numbers = [1, 2, 2, 3]
for number in numbers:
if number == 2:
numbers.remove(number)
print(numbers)
# Output:
# [1, 2, 3]Wait! One 2 is still in the list. Why?
Removing items while looping over a list can make Python skip items.
A loop moves through the list by position. When an item is removed, the items after it shift to the left. The loop then moves forward, which can cause it to skip the next item.
In this example, the first 2 is removed, and the second 2 shifts into its position. But the loop moves on, so that second 2 isn’t checked.
What’s the safer way?
Option 1: Use list comprehension
This is often the simplest solution when you want to remove every item that matches a condition.
numbers = [1, 2, 2, 3]
numbers = [n for n in numbers if n != 2]
print(numbers)
# Output:
# [1, 3]This creates a new list containing only the numbers that aren’t equal to 2.
Option 2: Loop over a copy
You can also loop over a copy of the list while removing items from the original.
numbers = [1, 2, 2, 3]
for number in numbers.copy():
if number == 2:
numbers.remove(number)
print(numbers)
# Output:
# [1, 3]We learned about copy(). The loop goes through the copy, while remove() changes the original list.
For filtering a list based on a condition, list comprehension is usually shorter and easier to read.
Looping Through a List in Reverse
Sometimes, you may want to process items from the end of a list to the beginning.
You can use reversed() to iterate through a list in reverse order without changing the original list.
fruits = ["apple", "banana", "cherry"]
for fruit in reversed(fruits):
print(fruit)
# Output:
# cherry
# banana
# appleNotice that the original list isn’t changed.
This is different from calling fruits.reverse(), which changes the order of the list itself.
👉 Try Project 6: To-Do List
👉 Next tutorial: Python Tuples