LearnPy Hub
Data StructuresBeginnerLesson 9 of 32

Lists

Watch the ideaA list is a row you can change
nums = [4, 8, 15]
nums
40
81
152

A list keeps items in order, each at an index.

1Level 1 · BasicsBasics

So far each variable has held one value. A list holds many values in order: all the marks in a class, every item in a cart. Lists are probably the data structure you'll use most.

Making a list

marks = [78, 91, 65, 88]
names = ["Rafi", "Sara", "Tuhin"]
empty = []

Lists use square brackets, with commas between items. A list can hold any types, even mixed, though usually all items are the same kind.

Indexing and slicing work just like strings

marks[0]      # 78   (first)
marks[-1]     # 88   (last)
marks[1:3]    # [91, 65]
len(marks)    # 4

Lists can change

Unlike strings, lists are mutable, so you can change them in place:

CodeWhat it does
marks[0] = 80replace an item
marks.append(70)add to the end
marks.insert(1, 99)insert at position 1
marks.remove(65)remove the first 65
marks.pop()remove and return the last item
marks.sort(), marks.reverse()sort / reverse in place

Handy functions

sum(marks), max(marks), min(marks) and len(marks) do what they say. sorted(marks) returns a new sorted list and leaves the original alone. 70 in marks checks membership.

Looping over a list

for m in marks:
    print(m)

for i, m in enumerate(marks):   # index and value together
    print(i, m)

Reading a list from input

Many problems give numbers on one line. This line turns "4 8 15" into [4, 8, 15]:

nums = list(map(int, input().split()))
Key points: lists are ordered and changeable; index from 0; append() adds; sort() changes the list but sorted() makes a new one; sum, max, min, len work on lists.

See it in actionA list is a row of numbered boxes

Watch boxes being added, replaced, sorted and removed.

Step-by-step

Try it yourselfExample 1: Basic list operations

Each operation changes the list. Watch it grow and get sorted.

example_1.py
Output appears here
Fill in the blanks

Add and count

Fill the blanks so mango is added to the end of the list and the program prints 3.

blanks.py
fruits = ["apple", "banana"]
fruits.("mango")
print((fruits))
Fix the bug

The last item

This should print the last score, 91, but it crashes. Fix it.

buggy.py

Example 2: Class average

sum() and len() give the average; a loop finds who scored above it.

example_2.py
Output appears here
Fill in the blanks

Class average

Fill the blanks so the program prints the average mark, 80.0.

blanks.py
marks = [70, 80, 90]
print((marks) / (marks))

Example 3: Read numbers from input

Change the numbers in the Input box.

example_3.py
Output appears here
Your turn

Highest and lowest

Read numbers on one line (like 4 9 1 7) and print the highest and lowest: Max: 9 Min: 1.

Example input4 9 1 7Expected outputMax: 9 Min: 1

my_code.py

Example 4: enumerate and building a new list

enumerate() gives position and value; append() builds a list of results.

example_4.py
Output appears here
Your turn

Keep the even numbers

Read numbers on one line and print a list of only the even ones, like [4, 2, 8] for 4 7 2 9 8.

Example input4 7 2 9 8Expected output[4, 2, 8]

my_code.py

2Level 2 · IntermediateSorting, searching and lists of lists

sort() vs sorted()

items.sort() changes the list itself and returns None; sorted(items) returns a new list. Both take reverse=True and a key, e.g. sorted(words, key=len).

Finding things

x in items, items.index(x) and items.count(x). index raises an error if x isn't there, so check with in first.

2-D lists (grids)

A list of lists is a table: grid[row][col]. Create it with a loop that appends a fresh row each time: for _ in range(3): grid.append([0] * 3). Never use [[0] * 3] * 3: that repeats the same inner list three times.

See it in actionThe [[0]*3]*3 trap

Watch how changing one cell of bad changes a whole column, while good changes one cell.

Step-by-step

Example 5: Sorting with a key

The key decides what to compare. Lists compare item by item, so putting the mark first sorts the students by mark.

example_5.py
Output appears here

Example 6: A grid of seats

Book a few seats, then print the hall. Row and column numbers start at 0.

example_6.py
Output appears here

3Level 3 · AdvancedCopies, performance and the right tool

Shallow vs deep copy

a.copy() or a[:] copies the outer list only; inner lists are shared. To copy everything, copy each inner list too. (The copy module, which you'll meet in the Modules lesson, has deepcopy() for this.)

What's fast and what's slow

Adding or removing at the end (append, pop()) is instant. Inserting or removing at the front (insert(0, x), pop(0)) shifts every item. x in list checks items one by one.

Stacks and queues

A list with append() and pop() is a stack: the last item in is the first out, like a browser's Back button. With pop(0) it becomes a queue: first in, first out. That is fine for small lists; later lessons show faster tools for big ones.

Slice assignment

a[1:3] = ["x", "y", "z"] replaces a section, even with a different length; del a[::2] deletes every other item.

See it in actionShallow copy shares the inner lists

Watch the arrows. shallow's inner lists are the same boxes as original's; deep has its own.

Step-by-step

Example 7: A stack and a queue with plain lists

The stack gives back the newest page; the queue serves the person who came first.

example_7.py
Output appears here

Example 8: Slice assignment

The list can grow or shrink through a slice.

example_8.py
Output appears here
Gotchab = a doesn't copy a list: both names point to the same list, so changing one changes the other. Make a real copy with b = a.copy() or b = a[:].
Exercise · predict the output

What does this print?

a = [1, 2, 3]
b = a
b.append(4)
print(len(a))
Quick quiz · 5 questions
1. Which adds an item to the end of a list?
2. What is [1, 2, 3][-1]?
3. What is the difference between nums.sort() and sorted(nums)?
4. How do you check whether 5 is in the list nums?
5. What does [10, 20, 30, 40][1:3] give?
Ready to practice lists?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Lists · LearnPy Hub