Lists

DATA STRUCTURES


Python Lists

Lists are one of the most commonly used data structures in Python. They allow storing multiple items in a single variable, and they are mutable, meaning their content can be modified. Lists support various operations, including adding, removing, sorting, and slicing elements.

Good for: Ordered collection, allows duplicates, mutable

Basic Operations

  • list.append(x) → Add an item to the end
my_list = [1, 2, 3]
my_list.append(4)
# Output: [1, 2, 3, 4]
  • list.extend(iterable) → Add multiple items
my_list.extend([5, 6])
# Output: [1, 2, 3, 4, 5, 6]
  • list.insert(i, x) → Insert at index
my_list.insert(2, 99)
# Output: [1, 2, 99, 3, 4, 5, 6]
  • list.remove(x) → Remove first occurrence
my_list.remove(99)
# Output: [1, 2, 3, 4, 5, 6]
  • list.pop([i]) → Remove and return item at index (default last)
last_item = my_list.pop()
# last_item: 6, my_list: [1, 2, 3, 4, 5]
  • list.clear() → Remove all elements
my_list.clear()
# Output: []
  • list.index(x[, start[, end]]) → Find index of first occurrence
index = [10, 20, 30, 40].index(30)
# Output: 2
  • list.count(x) → Count occurrences of a value
count = [1, 2, 2, 3, 3, 3].count(3)
# Output: 3
  • list.sort(key=None, reverse=False) → Sort in place
nums = [3, 1, 4, 1, 5]
nums.sort()
# Output: [1, 1, 3, 4, 5]
  • list.reverse() → Reverse the order
nums.reverse()
# Output: [5, 4, 3, 1, 1]
  • list.copy() → Create a shallow copy
new_list = nums.copy()
# Output: [5, 4, 3, 1, 1]

Slicing & Indexing

  • list[i] → Access element at index i
  • list[i:j] → Slice from i to j-1
  • list[i:j:k] → Slice with step k
  • list[-1] → Last element
nums = [10, 20, 30, 40, 50]
first = nums[0]  # Output: 10
last = nums[-1]  # Output: 50
slice = nums[1:4]  # Output: [20, 30, 40]

List Comprehension

squares = [x*x for x in range(5)]
# Output: [0, 1, 4, 9, 16]

Conversion

  • list(tuple/set) → Convert tuple/set to list
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
# Output: [1, 2, 3]