More List Methods

CDS1010: Week 4 Mini-Lecture
Wiedemann • Fall 2025

List Addition & Multiplication

  • The + operator concatenates lists.
  • The * operator replicates lists (repeated addition).
  • Both of these operations create a new list: they do not modify the original list.
# List Addition
list1 = ["A", "B"]
list2 = ["B", "C"]
result_addition = list1 + list2
print(result_addition)  # ["A", "B", "B", "C"]

# List Multiplication
list3 = ["A", "B"]
result_multiplication = list3 * 3
print(result_multiplication)  # ["A", "B", "A", "B", "A", "B"]

Append & Pop

  • list.append(x) adds an item to the end of a list
  • list.pop() removes and returns the last item
  • Notably, these methods both modify the original list.
cards = []
cards.append("A")
cards.append("K")
print(cards)  # ["A", "K"]

deck = cards * 4
print(deck)  # ["A", "K", "A", "K", "A", "K", "A", "K"]

top_card = deck.pop()  # removes and returns the last item
print(top_card)  # "K"
print(deck)  # ["A", "K", "A", "K", "A", "K", "A"]

Common List Methods

  • remove(x) deletes the first matching value
  • count(x) returns the number of copies of a value
  • index(x) returns the index of the first match
  • insert(i, x) places item at index i (shifts existing items to the right)
hand = ["5","K","5","A"]
hand.remove("5")  # remove the first "5", hand is now ["K", "5", "A"]
hand.insert(0, "Q")  # insert "Q" at index 0 (first position)
print(hand)  # ["Q", "K", "5", "A"]
print(hand.count("5"))  # 1

Reordering Lists

  • list.sort() puts a list in lexicographic order
  • list.reverse() reverses a list's current order
  • random.shuffle(list) randomly shuffles a list
  • Again, these methods modify the original list; they do not return a new list.
# To sort a list, use .sort()
hand = ["5","K","5","A"]
hand.sort()
print(hand)  # ["5", "5", "A", "K"]

# To shuffle a list, use random.shuffle()
valid_ranks = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
deck = valid_ranks * 4
random.shuffle(deck)  # deck is now shuffled