List methods
Lists come with methods for adding, removing and reorganising items. Most of them change the list in place and return None.
Adding items
Python
tasks = ["email"]
tasks.append("meeting") # add one item to the end
tasks.insert(0, "coffee") # insert at a position
tasks.extend(["lunch", "review"]) # add several items
print(tasks)append adds one item; extend adds each item of another collection. Appending a list puts the whole list in as one item:
Python
a = [1, 2]
a.append([3, 4])
print(a)
b = [1, 2]
b.extend([3, 4])
print(b)Removing items
Python
queue = ["Asha", "Leo", "Mei", "Raj", "Leo"]
queue.remove("Leo") # removes the FIRST matching value
print(queue)
last = queue.pop() # removes and returns the last item
print(last, queue)
first = queue.pop(0) # removes and returns the item at an index
print(first, queue)
del queue[0] # delete by index, returns nothing
print(queue)
queue.clear() # remove everything
print(queue)remove raises an error if the value is not there, so check with in first if you are unsure.
Sorting
Python
scores = [72, 95, 88, 61]
scores.sort() # sorts in place
print(scores)
scores.sort(reverse=True)
print(scores)
words = ["banana", "Apple", "cherry"]
words.sort(key=str.lower) # sort ignoring case
print(words)
names = ["Mei", "Alexandra", "Leo"]
print(sorted(names, key=len)) # sorted() returns a NEW list
print(names) # original unchangedReversing
Python
letters = ["a", "b", "c"]
letters.reverse() # in place
print(letters)
print(list(reversed(letters))) # new listQuick reference
| Method | Does |
|---|---|
append(x) | add x to the end |
insert(i, x) | add x at index i |
extend(items) | add every item |
remove(x) | delete the first x |
pop() / pop(i) | remove and return last / at i |
clear() | remove everything |
index(x) | position of the first x |
count(x) | how many times x appears |
sort() | sort in place |
reverse() | reverse in place |
copy() | shallow copy |
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.