Python List & Dict Methods

Advanced list and dictionary methods for data manipulation in Python.

List Methods

lst = [3, 1, 4, 1, 5, 9, 2]

lst.append(6)  # add to end: [3,1,4,1,5,9,2,6]
lst.insert(0, 0)  # insert at index 0: [0,3,1,4,1,5,9,2,6]
lst.extend([7, 8])  # add multiple items

lst.remove(1)  # remove first occurrence of 1
lst.pop()  # remove and return last item
lst.pop(0)  # remove and return item at index 0
lst.clear()  # remove all items

List Search & Sort

lst = [3, 1, 4, 1, 5, 9, 2]

# Search
lst.index(4)  # 2 (index of first 4)
lst.count(1)  # 2 (how many 1s)

# Sort
lst.sort()  # [1,1,2,3,4,5,9] (modifies list)
lst.sort(reverse=True)  # [9,5,4,3,2,1,1]
lst.reverse()  # reverse order in place

# Copy
lst2 = lst.copy()  # shallow copy
lst3 = lst[:]  # another way to copy

Dictionary Methods

d = {'a': 1, 'b': 2, 'c': 3}

# Access
d.get('a')  # 1
d.get('x', 0)  # 0 (default if not found)
d.keys()  # dict_keys(['a', 'b', 'c'])
d.values()  # dict_values([1, 2, 3])
d.items()  # dict_items([('a',1), ('b',2), ('c',3)])

Dict Modify

d = {'a': 1, 'b': 2}

# Update
d.update({'c': 3, 'd': 4})  # add multiple items
d.setdefault('e', 5)  # set if not exists

# Remove
d.pop('a')  # remove and return value of 'a'
d.popitem()  # remove and return last item
d.clear()  # remove all items

# Copy
d2 = d.copy()  # shallow copy