iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

List Methods

List methods reference. Lists are mutable — most methods change the list in place and return None.

Add

MethodWhat it does
append(x)Add x to the end.
extend(iter)Append each item from iter.
insert(i, x)Insert x at index i.

Remove

MethodWhat it does
remove(x)Remove first occurrence of x; raises ValueError if missing.
pop(i=-1)Remove and return item at i (default last).
clear()Remove everything.
del lst[i]Remove by index (statement, not method).

Search

MethodWhat it does
index(x, start=, stop=)First index of x; ValueError if missing.
count(x)How many.
x in lstMembership.

Reorder

MethodWhat it does
sort(key=, reverse=)Sort in place.
reverse()Reverse in place.
sorted(lst)NEW sorted list — does not mutate.

Copy

MethodWhat it does
copy()Shallow copy.
lst[:]Also shallow copy.
copy.deepcopy(lst)Deep copy of nested structures.

Slicing

PYTHON
lst[2:5]      # items 2 through 4
lst[:3]       # first three
lst[-3:]      # last three
lst[::2]      # every other
lst[::-1]     # reversed

Build with comprehensions

PYTHON
squares    = [n * n for n in range(10)]
evens_sqrd = [n * n for n in range(10) if n % 2 == 0]
matrix     = [[c for c in 'abc'] for _ in range(3)]
Tip: sort mutates and returns None. sorted returns a new list. nums.sort().reverse() is a common bug because sort() returns None.

Example

Example
a = [3, 1, 2]
a.append(4)
a.sort()
print(a)
print(a.index(2))
a.pop()
print(a)
print([x * 2 for x in a])
Try it Yourself »

Exercise

Append every item of an iterable to the list.

a. (b)

Test yourself

Q1. Reverse in place with…
Q2. Last item using slicing…
Q3. pop() default removes…

Discussion

Loading…