← Back to Blog

Lists — The Full Picture

You've covered lists from every angle. Before moving on, here's everything in one place.

// Creating lists

["a", "b", "c"]        # literal — values known upfront
[]                     # empty list
list()                 # empty list
list(range(1, 6))      # [1, 2, 3, 4, 5]
list("Bull")           # ['B', 'u', 'l', 'l']

// Indexing

sq = ["Raven", "Wolf", "Ghost"]
sq[0]      # Raven  — first element
sq[-1]     # Ghost  — last element
sq[1]      # Wolf

// Slicing — list[start:stop:step]

sq[1:3]    # ['Wolf', 'Ghost']
sq[:2]     # first 2 elements
sq[1:]     # from index 1 to end
sq[:]      # full copy
sq[::-1]   # reversed copy
sq[::2]    # every second element

// Adding elements

sq.append("Bull")       # add to end
sq.insert(1, "Viper")   # add at index
sq.extend(["a", "b"])   # add many

// Removing elements

sq.remove("Wolf")       # by value — ValueError if missing
sq.pop()                # remove last, returns it
sq.pop(1)               # remove by index
sq.clear()              # empty the list

// Sorting & reversing

sq.sort()               # ascending in place
sq.sort(reverse=True)   # descending in place
sq.reverse()            # flip in place
# sort() and reverse() return None — don't assign

// Inspecting

"Wolf" in sq            # True / False
"Fox" not in sq         # True / False
len(sq)                 # number of elements
sq.index("Ghost")       # position of first match
sq.count("Wolf")        # number of occurrences
min(scores)             # smallest (numbers only)
max(scores)             # largest (numbers only)
sum(scores)             # total (numbers only)

// Copying

backup = sq.copy()      # independent copy
backup = sq             # WRONG — same list, two names

// Iterating

for item in sq:
    print(item)

for i, item in enumerate(sq):
    print(i, item)

for a, b in zip(sq, other):
    print(a, b)

// Nested lists

grid = [[1, 2, 3], [4, 5, 6]]
grid[0]       # [1, 2, 3]
grid[0][1]    # 2

for row in grid:
    for item in row:
        print(item)

// split() — string to list

"a b c".split()          # ['a', 'b', 'c']
"a,b,c".split(",")       # ['a', 'b', 'c']
"a b c".split(" ", 1)    # ['a', 'b c']

// Common mistakes

sq = sq.append("x")     # None — don't assign mutating methods
sq[5] on a 3-item list  # IndexError
sq.remove("x")          # ValueError if not found — check with in first
sq.append(["a", "b"])   # nested list — use extend() instead
backup = sq             # same list — use .copy()
# modifying a list during a loop — unpredictable
sq[0:3]                 # stop is exclusive — gives indexes 0, 1, 2

That's lists. One structure. A lot of power.

The cheatsheet above is yours to download and keep.

[ login to bookmark ] // copied! 19 views · 2 min
// resources
Cheatsheet Lists — The Full Picture Cheatsheet Lists — The Full Picture
← prev Common Lists Mistakes next → This One's Yours — Lists
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.