List Methods

append, extend, insert, remove, pop, sort

Interview Relevant: Essential methods

List Methods

Common list manipulation methods.

Code Examples

Essential list methods.

python
1lst = [1, 2, 3]
2
3# Adding elements
4lst.append(4)        # [1, 2, 3, 4]
5lst.extend([5, 6])   # [1, 2, 3, 4, 5, 6]
6lst.insert(0, 0)     # [0, 1, 2, 3, 4, 5, 6]
7
8# Removing elements
9lst.remove(3)        # Remove first 3
10item = lst.pop()     # Remove and return last
11item = lst.pop(0)    # Remove and return at index
12lst.clear()          # Remove all
13
14# Searching
15lst = [1, 2, 3, 2, 1]
16lst.index(2)         # 1 (first occurrence)
17lst.count(2)         # 2 (count occurrences)
18
19# Sorting
20lst.sort()           # In-place ascending
21lst.sort(reverse=True)  # In-place descending
22lst.reverse()        # Reverse in-place
23
24# Copy
25new_lst = lst.copy()  # Shallow copy

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In