Lists let one variable carry a whole sequence of values, such as every item on a shopping slip or every mark in a class. You write them with square brackets, you can add or drop items at any time, and you can overwrite any item where it stands. Most Python programs reach for lists more than any other collection.
In this lesson you will learn
- How to create a list and read items by position
- How negative indexes and slices work
- How to add, remove and replace items
- Handy built-in functions for lists of numbers
- How to loop through a list and build new lists with comprehensions
- How nested lists work and how to copy a list safely
Creating a List and Reading Items
Put values inside square brackets, separated by commas. Each item gets a position number called an index, and counting starts at 0.
bazar = ["rice", "lentils", "onion", "egg", "green chilli"]
print(bazar)
print(len(bazar))
print(bazar[0])
print(bazar[-1])
Output
['rice', 'lentils', 'onion', 'egg', 'green chilli']
5
rice
green chilli
len() returns how many items the list holds. Index 0 gives the first item, and index -1 gives the last one. Negative indexes count backwards from the end, which saves you from writing bazar[len(bazar) - 1].
| Item | “rice” | “lentils” | “onion” | “egg” | “green chilli” |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
| Negative index | -5 | -4 | -3 | -2 | -1 |
Coming from C?
A C array has a fixed size and one element type. A Python list resizes itself automatically and can even mix types, such as [1, "two", 3.0]. In practice, keep one kind of item per list; it makes your code far easier to reason about.
Slicing: Taking Part of a List
A slice uses the pattern list[start:stop:step]. It begins at start, stops just before stop, and moves step items at a time. Any of the three parts can be left out.
week = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
print(week[1:4])
print(week[:2])
print(week[5:])
print(week[::2])
Output
['Sun', 'Mon', 'Tue']
['Sat', 'Sun']
['Thu', 'Fri']
['Sat', 'Mon', 'Wed', 'Fri']
week[1:4]takes indexes 1, 2 and 3. Index 4 is not included.week[:2]starts at the beginning becausestartis empty.week[5:]runs to the end becausestopis empty.week[::2]takes every second day. A step of-1, as inweek[::-1], gives the list reversed.
A slice always returns a new list and never raises an error for out-of-range numbers. week[3:100] simply returns everything from index 3 onward.
Adding, Removing and Replacing Items
Lists are mutable, meaning you can change them after they are created. These methods change the list in place.
playlist = ["Song A", "Song B", "Song C"]
playlist.append("Song D") # add to the end
playlist.insert(1, "Intro") # add at position 1
print(playlist)
playlist.remove("Song B") # remove by value
last = playlist.pop() # remove and return the last item
print(playlist)
print("Removed:", last)
playlist[0] = "Opening" # change an item
print(playlist)
Output
['Song A', 'Intro', 'Song B', 'Song C', 'Song D']
['Song A', 'Intro', 'Song C']
Removed: Song D
['Opening', 'Intro', 'Song C']
| Method | What it does | Example |
|---|---|---|
append(x) | Adds x to the end | nums.append(7) |
insert(i, x) | Puts x at index i, shifting the rest right | nums.insert(0, 1) |
extend(items) | Adds every item from another collection | nums.extend([8, 9]) |
remove(x) | Deletes the first item equal to x | nums.remove(7) |
pop(i) | Deletes and returns the item at i (last item if no index) | nums.pop() |
clear() | Empties the list | nums.clear() |
index(x) | Returns the position of the first x | nums.index(9) |
count(x) | Counts how many times x appears | nums.count(2) |
sort() | Sorts the list in place | nums.sort(reverse=True) |
reverse() | Reverses the order in place | nums.reverse() |
Useful Functions for Lists of Numbers
Python’s built-in functions work directly on lists, so common calculations take one line each. This example looks at a week of afternoon temperatures in °C.
temps = [31, 29, 34, 27, 33]
print("Highest:", max(temps))
print("Lowest:", min(temps))
print("Average:", sum(temps) / len(temps))
temps.sort()
print("Sorted:", temps)
print("Is 34 in the list?", 34 in temps)
Output
Highest: 34
Lowest: 27
Average: 30.8
Sorted: [27, 29, 31, 33, 34]
Is 34 in the list? True
The in operator returns True or False depending on whether a value appears in the list. Use sorted(temps) instead of temps.sort() when you want a sorted copy and need to keep the original order.
Looping Through a List
A for loop visits each item in order. When you also need the position, wrap the list in enumerate().
orders = [250, 1200, 480, 3000]
for amount in orders:
if amount >= 1000:
print(amount, "taka - free delivery")
else:
print(amount, "taka - delivery 60 taka")
for i, amount in enumerate(orders, start=1):
print(f"Order {i}: {amount} taka")
Output
250 taka - delivery 60 taka
1200 taka - free delivery
480 taka - delivery 60 taka
3000 taka - free delivery
Order 1: 250 taka
Order 2: 1200 taka
Order 3: 480 taka
Order 4: 3000 taka
The second loop uses an f-string: text that starts with f can hold variables inside curly braces. start=1 makes the numbering begin at 1 instead of 0, which reads more naturally for customers.
List Comprehensions
A list comprehension builds a new list from an existing one in a single, readable line. The general form is [expression for item in list if condition].
prices = [100, 250, 75, 400]
with_vat = [round(p * 1.15, 2) for p in prices]
print(with_vat)
cheap = [p for p in prices if p < 200]
print(cheap)
Output
[115.0, 287.5, 86.25, 460.0]
[100, 75]
The first comprehension adds 15% VAT to each price and rounds to two decimals. The second keeps only prices under 200. Without comprehensions, each would need an empty list, a loop and an append() call.
Nested Lists
An item in a list can itself be a list. This is a simple way to store rows and columns, such as seats in a bus or a small grid.
seats = [
["A1", "A2", "A3"],
["B1", "B2", "B3"],
]
print(seats[1][2])
for row in seats:
print(" ".join(row))
Output
B3
A1 A2 A3
B1 B2 B3
seats[1] selects the second row, and the extra [2] picks the third seat in that row. " ".join(row) glues the strings in a row together with a space between them.
Copying a List the Right Way
As you saw in the Variables lesson, b = a does not copy a list. It gives the same list a second name. Use .copy() (or a[:]) when you need an independent list.
original = [1, 2, 3]
alias = original
copy_list = original.copy()
original.append(4)
print("alias:", alias)
print("copy:", copy_list)
Output
alias: [1, 2, 3, 4]
copy: [1, 2, 3]
alias changed along with original because they are the same list. copy_list did not, because it is a separate list. For nested lists, .copy() copies only the outer level; use copy.deepcopy() from the copy module to copy every level.
Common Mistakes
- Off-by-one indexes. The last item of a 5-item list is at index 4, not 5.
bazar[5]raisesIndexError. - Saving the result of
sort().result = nums.sort()storesNone, becausesort()changes the list and returns nothing. Usesorted(nums)if you need a return value. - Removing a value that is not there.
remove("mango")raisesValueErrorif the item is missing. Check withinfirst. - Changing a list while looping over it. Removing items inside
for item in items:skips elements. Loop over a copy, or build a new list with a comprehension. - Mixing up
append()andextend().a.append([1, 2])adds one item (a list).a.extend([1, 2])adds two items.
Best Practices
- Use plural names for lists, such as
ordersorstudent_names, and singular names for loop variables. - Prefer
for item in itemsoverfor i in range(len(items))unless you truly need the index; when you do, useenumerate(). - Reach for a comprehension when building one list from another, but switch to a normal loop if the line becomes hard to read.
- Copy deliberately. Decide whether you want a second name or a second list.
Practice Exercises
Exercise 1. Given fruits = ["mango", "jackfruit", "lychee", "guava"], print the second fruit and the last fruit.
Show answer
print(fruits[1]) # jackfruit
print(fruits[-1]) # guava
Exercise 2. Add "banana" to the end of fruits, then remove "lychee". What does the list contain now?
Show answer
fruits.append("banana")
fruits.remove("lychee")
print(fruits) # ['mango', 'jackfruit', 'guava', 'banana']
Exercise 3. Use a list comprehension to get the squares of the numbers 1 to 5.
Show answer
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Exercise 4. What does [10, 20, 30, 40, 50][::-2] return?
Show answer
[50, 30, 10]. The step of -2 starts from the end and takes every second item.
Frequently Asked Questions
What is the difference between a list and a tuple?
A list can be changed after it is created; a tuple cannot. Lists use square brackets [] and tuples use round brackets (). Use a tuple for fixed groups of values, such as coordinates.
Can a Python list hold different data types?
Yes. A list can hold numbers, strings, other lists and any other object together. It is still good practice to keep one kind of item per list.
How do I check if a list is empty?
An empty list counts as false, so if not items: is true when the list has no items. len(items) == 0 works too.
Is a Python list the same as an array?
Not exactly. A list is a flexible, resizable collection of any objects. For large amounts of numeric data, the NumPy library provides true arrays that are faster and use less memory.
Summary
- Lists are ordered, changeable collections written with
[], indexed from 0. - Negative indexes count from the end; slices use
[start:stop:step]and excludestop. append(),insert(),remove()andpop()change a list in place.len(),max(),min(),sum()andinwork directly on lists.- Comprehensions build new lists in one line;
.copy()makes an independent list.
