Programmer's Picnic · Python Foundations · 0 → ∞
Python Lists: From 0 to Infinity
Store several values, change them safely and turn them into practical algorithms.
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.
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.
fruits = ['mango', 'guava', 'mango']
print(fruits)
print(len(fruits))
print(type(fruits).__name__)['mango', 'guava', 'mango']
3
listRemember: Use [] for an empty list. list('cat') makes ['c', 'a', 't'].
1 · Index, membership, slice
Indexing uses zero-based positions and negative positions from the end. A slice [start:stop:step] creates a new list.
scores = [42, 87, 65, 91, 73]
print(scores[0], scores[-1])
print(scores[1:4])
print(scores[::-1])
print(91 in scores)42 73
[87, 65, 91]
[73, 91, 65, 87, 42]
TrueRemember: Indexing outside the list raises IndexError. Slice bounds are forgiving.
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.
items = ['pen', 'book']
items[0] = 'pencil'
items.append('eraser')
items.extend(['ruler', 'clip'])
items.insert(1, 'bag')
print(items)['pencil', 'bag', 'book', 'eraser', 'ruler', 'clip']Remember: append([1, 2]) adds a nested list; extend([1, 2]) adds two separate elements.
3 · Remove items carefully
pop() removes and returns by index (last by default). remove() deletes the first matching value. clear() empties a list.
nums = [2, 4, 4, 6]
last = nums.pop()
nums.remove(4)
print(last)
print(nums)6
[2, 4]Remember: remove(99) raises ValueError when 99 is absent. Check membership or handle exceptions.
4 · Loops and enumerate
Iterate through elements directly. enumerate() gives both position and value; use it instead of manually updating a counter.
cities = ['Ranchi', 'Patna', 'Varanasi']
for position, city in enumerate(cities, start=1):
print(position, city)1 Ranchi
2 Patna
3 VaranasiRemember: Avoid changing the length of the same list while iterating over it; build a new list instead.
5 · List comprehensions
A comprehension builds a new list from an iterable, optionally filtering items. Keep complex operations in a named function for clarity.
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)[1, 4, 9, 16, 25]
[2, 4]Remember: A comprehension creates a list in memory; use a generator expression for streaming when suitable.
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.
names = ['meera', 'Asha', 'kabir']
print(sorted(names, key=str.casefold))
numbers = [12, 3, 8]
numbers.sort(reverse=True)
print(numbers)['Asha', 'kabir', 'meera']
[12, 8, 3]Remember: Do not write result = items.sort(): result will be None. See the dedicated list-sorting lesson.
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.
a = [[1], [2]]
b = a.copy()
b[0].append(99)
print(a)
print(a is b)[[1, 99], [2]]
FalseRemember: For nested structures, import copy; copy.deepcopy(a) when deep independence is required.
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.
grid = [[0 for col in range(3)] for row in range(2)]
grid[0][1] = 7
print(grid)[[0, 7, 0], [0, 0, 0]]Remember: Avoid [[0] * 3] * 2 for a mutable grid: both rows refer to the same object.
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.
from collections import deque
queue = deque(['A', 'B'])
queue.append('C')
print(queue.popleft())
print(list(queue))A
['B', 'C']Remember: Membership search in a general list is O(n). Index access is O(1).
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.
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)Passed: 3
Top: 91
Average: 67.8Remember: Extension: make a function that also returns the count in score bands 0–49, 50–74 and 75–100.
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
| Type | Ordered? | Mutable? | Duplicates? | Best for |
|---|---|---|---|---|
| str | Yes | No | Yes | Text |
| list | Yes | Yes | Yes | Changing sequences |
| tuple | Yes | No* | Yes | Fixed records |
| set | No guaranteed order | Yes | No | Unique membership |
| dict | Insertion order | Yes | Keys unique | Named lookups |
* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.
Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.