Lists provide methods that change the list in place. Most of them return None, so assigning their result to a variable is a common mistake.
Adding items#
items = ["a", "b"]
items.append("c") # add one item at the end
items.extend(["d", "e"]) # add every item from another iterable
items.insert(0, "start") # insert at a position
print(items)['start', 'a', 'b', 'c', 'd', 'e']
append(["d", "e"]) would add the entire list as a single nested item. Use extend() to add the elements individually.
Removing items#
items = ["a", "b", "c", "b"]
items.remove("b") # remove the first matching value
last = items.pop() # remove and return the last item
first = items.pop(0) # remove and return the item at index 0
items.clear() # remove every item
print(last, first)b a
remove() raises ValueError if the value is absent. pop() raises IndexError when the list is empty or the index is invalid. Check with in or handle the exception when absence is possible.
Finding items#
items = ["a", "b", "c", "b"]
print(items.index("b")) # 1: first occurrence
print(items.count("b")) # 2Both methods raise or return zero based on the data; index() raises ValueError when the value is missing.
Sorting#
numbers = [4, 1, 3, 2]
numbers.sort() # in place
print(numbers) # [1, 2, 3, 4]
numbers.sort(reverse=True)
print(numbers) # [4, 3, 2, 1]
words = ["banana", "apple", "cherry"]
print(sorted(words, key=len)) # ['apple', 'banana', 'cherry']sort() modifies the list and returns None. sorted() returns a new list and leaves the original unchanged. Both are stable, so equal elements keep their relative order.
Sorting mixed types such as integers and strings raises TypeError on Python 3. Convert to a common key first.
Reversing#
values = [1, 2, 3]
values.reverse()
print(values) # [3, 2, 1]
copy = values[::-1] # new reversed listAgain, reverse() changes the original and returns None.
Joining and splitting#
Lists and strings meet through join() and split():
words = ["Python", "is", "readable"]
sentence = " ".join(words)
print(sentence) # Python is readable
parts = sentence.split()
print(parts) # ['Python', 'is', 'readable']join() is a string method. Every item must be a string; convert numbers with map(str, numbers) first.
A complete example#
scores = [88, 92, 79, 92, 65]
scores.append(100)
scores.remove(65)
scores.sort(reverse=True)
print(scores)
print("Highest:", scores[0])
print("Count of 92:", scores.count(92))
print("Average:", sum(scores) / len(scores))Practice#
Start with an empty shopping list. Add three items, insert one at the front, remove one by name, and sort the result alphabetically. Print the list after each step so you can see the effect of each method.
