Learn Without Walls
← Back to Module 6

Module 6: Lists -- Quick Reference

A printable reference card covering list creation, methods, slicing, and comprehensions.

Creating Lists

SyntaxDescriptionExample
[]Empty listitems = []
[a, b, c]List with valuesnums = [1, 2, 3]
list()Empty list (constructor)items = list()
list(iterable)Convert to listlist("abc") → ["a","b","c"]
list(range(n))List from rangelist(range(5)) → [0,1,2,3,4]

Accessing Elements

SyntaxDescriptionExample (lst = [10,20,30,40,50])
lst[0]First element10
lst[-1]Last element50
lst[-2]Second to last40
len(lst)Number of items5
x in lstMembership check30 in lst → True
x not in lstNot in check99 not in lst → True

List Methods

MethodDescriptionReturns
lst.append(x)Add x to the endNone
lst.insert(i, x)Insert x at index iNone
lst.extend(iter)Add all items from iterableNone
lst.remove(x)Remove first occurrence of xNone
lst.pop()Remove and return last itemThe item
lst.pop(i)Remove and return item at iThe item
lst.clear()Remove all itemsNone
lst.sort()Sort ascending in placeNone
lst.sort(reverse=True)Sort descending in placeNone
lst.reverse()Reverse order in placeNone
lst.count(x)Count occurrences of xInteger
lst.index(x)Index of first xInteger
lst.copy()Shallow copyNew list

Slicing

SyntaxDescriptionExample (lst = [0,1,2,3,4,5,6,7,8,9])
lst[a:b]From index a to b-1lst[2:5] → [2,3,4]
lst[:b]From start to b-1lst[:3] → [0,1,2]
lst[a:]From a to endlst[7:] → [7,8,9]
lst[:]Copy entire listlst[:] → [0,1,...,9]
lst[::n]Every nth elementlst[::2] → [0,2,4,6,8]
lst[::-1]Reversed copylst[::-1] → [9,8,...,0]
lst[-3:]Last 3 elementslst[-3:] → [7,8,9]

List Comprehensions

PatternSyntaxExample
Basic[expr for x in iter][x**2 for x in range(5)]
With filter[expr for x in iter if cond][x for x in nums if x > 0]
With if/else[A if cond else B for x in iter]["even" if x%2==0 else "odd" for x in nums]

Built-in Functions for Lists

FunctionDescriptionExample
len(lst)Number of itemslen([1,2,3]) → 3
sum(lst)Sum of itemssum([1,2,3]) → 6
min(lst)Smallest itemmin([3,1,2]) → 1
max(lst)Largest itemmax([3,1,2]) → 3
sorted(lst)New sorted listsorted([3,1,2]) → [1,2,3]
reversed(lst)Reverse iteratorlist(reversed([1,2,3])) → [3,2,1]