Lists and tuples
Lists and tuples in Python: sequence types, indexing, slicing, mutability vs immutability, methods, packing/unpacking, comprehensions, sorting, copying, and common exam-program patterns.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers store and process collections of values all the time: sensor readings, coordinates, test results, or file names. Python’s lists and tuples are the standard sequence types to hold such ordered data, so you must know how to create them, access elements fast, slice parts, sort them, and avoid common bugs.
Key ideas
- Definition: A list is a mutable (changeable) sequence of objects, written with square brackets, e.g.,
[10, 20, 30]. “Mutable” means we can insert, delete, or replace elements after creation. - Definition: A tuple is an immutable (not changeable) sequence of objects, written with parentheses, e.g.,
(10, 20, 30). “Immutable” means once created, its length and elements cannot be changed. - Definition: Indexing is accessing an element by its position. Python uses zero-based indexing: the first element is at index 0, the second at index 1, and so on. Negative indices count from the end:
-1is the last element,-2is the second last. - Definition: Slicing selects a part (subsequence) using
start:stop:step. It includes the element atstartindex, but excludes the element atstop. The default step is 1. Negative steps traverse backwards. - Definition: Mutability is the property that allows changing the object in place. Lists are mutable; tuples are immutable.
- Definition: Immutability means the object cannot be changed after creation. Any “change” creates a new object instead, leaving the original as-is. Tuples are immutable. This often makes tuples safe to use as dictionary keys and set elements if all their elements are also hashable.
- Definition: Membership test uses
inandnot into check if a value is present in a sequence, returning a Boolean (TrueorFalse). - Definition: Concatenation joins two sequences of the same type using
+. Repetition repeats a sequence using*with an integer n; if n <= 0 the result is an empty sequence. - Definition: Aliasing occurs when two variables refer to the same object in memory. Modifying through one name affects the other. Example:
b = aaliasesbto the same list asa. - Definition: Shallow copy creates a new outer container but does not recursively copy nested objects. Methods: slicing
a[:],list(a),a.copy(). For nested lists, inner lists are still shared. A deep copy recursively copies nested objects; usecopy.deepcopy(a)from thecopymodule. - Definition: Packing creates a tuple from comma-separated values:
t = 1, 2, 3. Parentheses are optional except in certain expressions. Unpacking assigns elements of a sequence to variables:x, y, z = t. Extended unpacking uses*rest:head, *mid, tail = [1, 2, 3, 4]. - Definition: One-element tuple syntax requires a trailing comma:
(10,)is a tuple with one element;(10)is just the integer 10 in parentheses. - Definition: List comprehension builds a new list by looping and optionally filtering in a single expression:
[expr for item in iterable if condition]. This is preferred for clear, concise transformations. - Definition: Tuple methods: tuples support
.count(value)and.index(value)only. They have few methods due to immutability. List methods include.append,.extend,.insert,.remove,.pop,.clear,.index,.count,.sort,.reverse,.copy. - Definition: Stable sort: Python’s
list.sort()andsorted()are stable, meaning when two keys compare equal, their original order is preserved. Sorting can take akey=functionandreverse=True/False. - Definition: Lexicographic comparison compares sequences element by element from left to right; the first unequal element decides the result. If all compared elements are equal up to the length of the shorter sequence, the shorter sequence is considered smaller.
- Definition: Hashability and tuples: A tuple is hashable only if all its elements are hashable (e.g., numbers, strings, other tuples of hashable items). Lists are not hashable because they are mutable.
- Definition: Range and sequences:
range(start, stop, step)is an immutable sequence of integers often used with loops. Convert to a list usinglist(range(...))if needed. The step cannot be 0. - Safety note: Avoid
*repetition for creating nested lists like[[0]*3]*2because the inner lists are aliased; modifying one row modifies all. Prefer a comprehension:[[0 for _ in range(3)] for _ in range(2)].
Exact statements to remember for exams
- Zero-based indexing rule: In Python, the first element of any sequence is at index 0. Negative indices access from the end, with
-1as the last element. - Slicing rule: For
s[start:stop:step], the slice includes indicesisuch thatistarts atstart, increases bystep, andi < stopifstep > 0(ori > stopifstep < 0). Thestopindex is excluded. Step cannot be 0 (raises ValueError). - Immutability rule for tuples: A tuple’s elements and length cannot be changed after creation; operations that appear to modify a tuple create a new tuple object.
- Stability rule for sorting: If
AandBhave equal keys,list.sort()andsorted()preserve their relative order from the original list.
Exam diagram (what to draw and label)
- For a question on aliasing vs shallow copy vs deep copy, draw three small boxes:
- Aliasing: Draw one list object box with two arrows labeled
aandbpointing to the same box. - Shallow copy: Draw two outer list boxes
aandb, with their first elements both pointing to the same inner list box; label the shared inner object to show sharing. - Deep copy: Draw two outer list boxes
aandb, each pointing to separate inner list boxes; label them as distinct copies. Label arrows as “references”. Label inner boxes “nested list”.
- Aliasing: Draw one list object box with two arrows labeled
Formulas
T = (item1, item2, ...)Create a tuple.t1 = 10, 20Tuple packing without parentheses.single = (10,)One-element tuple needs a comma.x = L[i]Indexing (0-based). Negative index allowed.sub = L[start:stop:step]Slicing. Defaults: if step is omitted, step=1; if step > 0 and start/stop are omitted: start=0, stop=len(L); if step < 0 and start/stop are omitted: start=len(L)-1, stop=-1 (one before the first index). Note: step cannot be 0.L[i] = valueReplace element in a list.L.append(x)Add an element to the end.L.extend(iterable)Append all elements from iterable to list.L.insert(i, x)Insert before index i.L.remove(x)Remove first occurrence of x; raises ValueError if not found.x = L.pop()Remove and return last element;L.pop(i)removes and returns element at index i.L.clear()Remove all elements.pos = L.index(x)Position of first occurrence of x; raises ValueError if not found.cnt = L.count(x)Count occurrences of x.L.sort(key=None, reverse=False)In-place sort; returns None.L.reverse()In-place reverse; returns None.new = sorted(iterable, key=None, reverse=False)Return new sorted list.rev = L[::-1]Create a reversed copy via slicing.T.count(x), T.index(x)Tuple methods available.a, b = b, aSwap using tuple unpacking.head, *mid, tail = seqExtended unpacking.L2 = L[:]orL.copy()Shallow copy of a list.import copy; deep = copy.deepcopy(L)Deep copy.[expr for x in iterable if condition]List comprehension.tuple(L)andlist(T)Type conversion between list and tuple.x in seq,x not in seqMembership test.seq1 + seq2,seq * nConcatenate, repeat (n is an integer; if n <= 0, the result is empty).
Worked examples
Example 1: Basic list and tuple operations, indexing, slicing, and aggregation Program: Read space-separated integers from one line. Show indexing, slicing, reverse, counts, and convert to tuple.
# Example 1: Lists, tuples, indexing, slicing, and built-ins
# Input: one line with space-separated integers
# Read a line of input and split into integers
line = input().strip()
L = [int(x) for x in line.split()] # list of ints
print("List L:", L)
print("First element L[0]:", L[0])
print("Last element L[-1]:", L[-1])
print("Slice L[1:4]:", L[1:4])
print("Reversed L[::-1]:", L[::-1])
# Count occurrences of a chosen value if present; here we choose the first value
value = L[0]
print(f"Count of {value}:", L.count(value))
# Convert to tuple and show sum, min, max
T = tuple(L)
print("Tuple T:", T)
print("Sum:", sum(L))
print("Min:", min(L))
print("Max:", max(L))
Sample input
10 3 5 8 3
Exact output
List L: [10, 3, 5, 8, 3]
First element L[0]: 10
Last element L[-1]: 3
Slice L[1:4]: [3, 5, 8]
Reversed L[::-1]: [3, 8, 5, 3, 10]
Count of 10: 1
Tuple T: (10, 3, 5, 8, 3)
Sum: 29
Min: 3
Max: 10
Example 2: Sorting a list of tuples using key and reverse; tuple unpacking Program: Read N student records (name string, marks integer). Sort by marks descending, then by name ascending. Print sorted list and the top scorer(s).
# Example 2: Sort list of (name, marks) tuples
n = int(input().strip())
records = []
for _ in range(n):
name, marks = input().split()
records.append((name, int(marks)))
# Sort by marks descending, then name ascending
records.sort(key=lambda t: (-t[1], t[0]))
print("Sorted records:", records)
# Find top mark and print all toppers using unpacking
top_mark = records[0][1]
toppers = [name for (name, m) in records if m == top_mark]
print("Top mark:", top_mark)
print("Toppers:", toppers)
Sample input
4
Asha 78
Ravi 85
Irfan 85
Meera 62
Exact output
Sorted records: [('Irfan', 85), ('Ravi', 85), ('Asha', 78), ('Meera', 62)]
Top mark: 85
Toppers: ['Irfan', 'Ravi']
Example 3: Aliasing vs shallow copy vs deep copy with nested lists Program: Show how modifying nested inner lists affects shallow and deep copies.
# Example 3: Aliasing vs shallow copy vs deep copy
import copy
nested = [[1, 2], [3, 4]]
aliased = nested # aliasing (same object)
shallow = list(nested) # shallow copy of outer list
deep = copy.deepcopy(nested) # deep copy of entire structure
# Mutate an inner element
nested[0][0] = 99
# Append a new inner list to original
nested.append([5, 6])
print("Original nested:", nested)
print("Aliased (same as nested):", aliased)
print("Shallow copy:", shallow)
print("Deep copy:", deep)
No input Exact output
Original nested: [[99, 2], [3, 4], [5, 6]]
Aliased (same as nested): [[99, 2], [3, 4], [5, 6]]
Shallow copy: [[99, 2], [3, 4]]
Deep copy: [[1, 2], [3, 4]]
Explanation: Changing nested[0][0] modifies the shared inner list, so both aliased and shallow show [99, 2] in the first inner list. Appending a new inner list changes only nested (and aliased); shallow keeps original outer elements, and deep remains completely original.
Common mistakes
- Misusing negative indices:
L[-0]equalsL[0]; some expect an error or last element. - Forgetting the comma in a one-element tuple: writing
(10)(this is just 10), not(10,). - Trying to modify a tuple:
T[0] = 5raisesTypeErrorbecause tuples are immutable. - Confusing aliasing with copying: doing
b = aand then being surprised thatbchanges whenachanges. - Shallow copy with nested lists: using
a.copy()and expecting inner lists to be independent; they are not. - Using
*with lists of lists:rows = [[0]*3]*2creates two references to the same inner list; changing one row changes the other. - Assuming
list.sort()returns a new list: it returnsNone. Usesorted(L)to get a new list. - Ignoring stable sort behavior: writing complicated tie-break code when simply using a tuple key like
key=lambda t: (tiebreak1, tiebreak2)would work with stability. - Misunderstanding
removevspop:remove(x)deletes by value;pop(i)removes by index and returns the element. - Using a list as a dictionary key or in a set: lists are unhashable; use a tuple of hashable items instead.
For your exam
- Short notes: Differences between list and tuple (syntax, mutability, methods, typical use-cases, hashability), list methods with one-line function, time to hint complexity only if asked; otherwise focus on behavior and return values (e.g.,
list.sort()returns None,sorted()returns new list). - Programs: Typical tasks include reading numbers, filtering even/odd, finding max/min/sum, removing duplicates while preserving order, sorting records by multiple keys, reversing a list, slicing patterns, converting list to tuple and back, demonstrating shallow vs deep copy.
- Diagrams: For aliasing and copying, draw reference diagrams as described above. Label variables and objects clearly.
- Best-practice points to earn full marks:
- Use clear variable names.
- Show sample I/O if asked.
- Use built-ins (
sum,min,max,sorted,enumerate,zip) where appropriate. - For sorting by multiple criteria, use a tuple key or stable sort with secondary keys.
- When demonstrating copying, explicitly import
copyand show both shallow and deep copies with nested data. - When showing tuple packing/unpacking, include the one-element tuple case.
Quick check
- Write Python code to get the last three elements of a list
Lwithout raising an error ifLhas fewer than three elements. - How do you create a tuple containing only the string "ECE"? Show the exact syntax.
- After
rows = [[0]*3]*2, why doesrows[0][0] = 1also changerows[1][0]? How can you fix the initialization?
Answers: (1) tail = L[-3:] (works even if len(L) < 3); (2) ('ECE',) (note the trailing comma); (3) Because both rows refer to the same inner list (aliasing due to repetition); fix by using a comprehension: rows = [[0 for _ in range(3)] for _ in range(2)].
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?