Programmer's Picnic · Python Foundations · 0 → ∞

Python Lists: From 0 to Infinity

Store several values, change them safely and turn them into practical algorithms.

Free course · 60–80 minutes reading and practice · No installation beyond Python 3

How to learn

Read one level, type the code into the editor, predict the output, then run it. Change one line and observe the result before proceeding. All code examples work with standard Python 3 (the dictionary union example requires 3.9 or newer).

The course moves from first principles to realistic code, common mistakes, performance and a mini-project.

Level 0 / 10

0 · Lists in everyday life

A list is an ordered, mutable sequence. It can hold repeated values and even different types, though a consistent type is usually easier to maintain.

Python 3 · runnable example
fruits = ['mango', 'guava', 'mango']
print(fruits)
print(len(fruits))
print(type(fruits).__name__)
Expected output
['mango', 'guava', 'mango']
3
list

Remember: Use [] for an empty list. list('cat') makes ['c', 'a', 't'].

Level 1 / 10

1 · Index, membership, slice

Indexing uses zero-based positions and negative positions from the end. A slice [start:stop:step] creates a new list.

Python 3 · runnable example
scores = [42, 87, 65, 91, 73]
print(scores[0], scores[-1])
print(scores[1:4])
print(scores[::-1])
print(91 in scores)
Expected output
42 73
[87, 65, 91]
[73, 91, 65, 87, 42]
True

Remember: Indexing outside the list raises IndexError. Slice bounds are forgiving.

Level 2 / 10

2 · Change and add items

Assign by index to replace values; append adds one item, extend adds each element of an iterable, and insert places a value before an index.

Python 3 · runnable example
items = ['pen', 'book']
items[0] = 'pencil'
items.append('eraser')
items.extend(['ruler', 'clip'])
items.insert(1, 'bag')
print(items)
Expected output
['pencil', 'bag', 'book', 'eraser', 'ruler', 'clip']

Remember: append([1, 2]) adds a nested list; extend([1, 2]) adds two separate elements.

Level 3 / 10

3 · Remove items carefully

pop() removes and returns by index (last by default). remove() deletes the first matching value. clear() empties a list.

Python 3 · runnable example
nums = [2, 4, 4, 6]
last = nums.pop()
nums.remove(4)
print(last)
print(nums)
Expected output
6
[2, 4]

Remember: remove(99) raises ValueError when 99 is absent. Check membership or handle exceptions.

Level 4 / 10

4 · Loops and enumerate

Iterate through elements directly. enumerate() gives both position and value; use it instead of manually updating a counter.

Python 3 · runnable example
cities = ['Ranchi', 'Patna', 'Varanasi']
for position, city in enumerate(cities, start=1):
    print(position, city)
Expected output
1 Ranchi
2 Patna
3 Varanasi

Remember: Avoid changing the length of the same list while iterating over it; build a new list instead.

Level 5 / 10

5 · List comprehensions

A comprehension builds a new list from an iterable, optionally filtering items. Keep complex operations in a named function for clarity.

Python 3 · runnable example
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
print(squares)
print(evens)
Expected output
[1, 4, 9, 16, 25]
[2, 4]

Remember: A comprehension creates a list in memory; use a generator expression for streaming when suitable.

Level 6 / 10

6 · Sorting and order

sort() changes a list in place and returns None. sorted() returns a new list. key= defines the comparison value; Python sorting is stable.

Python 3 · runnable example
names = ['meera', 'Asha', 'kabir']
print(sorted(names, key=str.casefold))
numbers = [12, 3, 8]
numbers.sort(reverse=True)
print(numbers)
Expected output
['Asha', 'kabir', 'meera']
[12, 8, 3]

Remember: Do not write result = items.sort(): result will be None. See the dedicated list-sorting lesson.

Level 7 / 10

7 · Copying vs aliasing

Assignment copies a reference, not the data. list.copy() or [:] makes a shallow copy, so nested lists are still shared. Use deepcopy for independent nested content.

Python 3 · runnable example
a = [[1], [2]]
b = a.copy()
b[0].append(99)
print(a)
print(a is b)
Expected output
[[1, 99], [2]]
False

Remember: For nested structures, import copy; copy.deepcopy(a) when deep independence is required.

Level 8 / 10

8 · Nested lists as tables

Represent grids using lists of rows. Always use a comprehension to build independent nested lists; multiplication duplicates references to the same row.

Python 3 · runnable example
grid = [[0 for col in range(3)] for row in range(2)]
grid[0][1] = 7
print(grid)
Expected output
[[0, 7, 0], [0, 0, 0]]

Remember: Avoid [[0] * 3] * 2 for a mutable grid: both rows refer to the same object.

Level 9 / 10

9 · Stacks, queues and Big-O

append()/pop() at the right end usually cost amortised O(1). Inserting or removing near the front requires shifting items, O(n). For a FIFO queue use collections.deque.

Python 3 · runnable example
from collections import deque
queue = deque(['A', 'B'])
queue.append('C')
print(queue.popleft())
print(list(queue))
Expected output
A
['B', 'C']

Remember: Membership search in a general list is O(n). Index access is O(1).

Level 10 / 10

10 · Mini-project: marks dashboard

Build a summary from a class's marks. Filtering, aggregation and a defensive empty-list check are useful real-life skills.

Python 3 · runnable example
marks = [88, 42, 76, 91, 42]
passed = [m for m in marks if m >= 50]
print('Passed:', len(passed))
print('Top:', max(marks) if marks else 'No data')
print('Average:', round(sum(marks) / len(marks), 1) if marks else 0)
Expected output
Passed: 3
Top: 91
Average: 67.8

Remember: Extension: make a function that also returns the count in score bands 0–49, 50–74 and 75–100.

Practice lab

Test your understanding

Predict or explain the answer before opening the solution. Try rewriting one of the examples without copying it.

1. What is the difference between append([3,4]) and extend([3,4])?

Answer: append adds one nested object; extend adds two elements.

Inspect the resulting length.

2. Does sorted(my_list) modify my_list?

Answer: No; it returns a new sorted list.

sort() mutates.

3. Why is [[0]*3]*2 risky?

Answer: Both inner rows refer to the same list.

Use a comprehension to make independent rows.

Take it further: expand the mini-project with an input() prompt, a reusable function, input validation and three tests (normal, empty and boundary cases).

When to use each Python collection

Comparison of Python built-in data types
TypeOrdered?Mutable?Duplicates?Best for
strYesNoYesText
listYesYesYesChanging sequences
tupleYesNo*YesFixed records
setNo guaranteed orderYesNoUnique membership
dictInsertion orderYesKeys uniqueNamed lookups

* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.

Python official built-in types reference ↗

Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.