A Python list holds several values in order, under one name. It is the collection you will reach for most often.
tasks = ["study", "code", "rest"]
print(tasks[0]) # study
print(len(tasks)) # 3Indexing and slicing#
letters = ["a", "b", "c", "d", "e"]
print(letters[0]) # a — first
print(letters[-1]) # e — last
print(letters[1:3]) # ['b', 'c'] — from 1 up to (not including) 3
print(letters[:2]) # ['a', 'b']
print(letters[2:]) # ['c', 'd', 'e']
print(letters[::-1]) # reversed copySlices never error on out-of-range values — letters[1:99] simply gives you what exists. Single indexes do error, with IndexError: list index out of range.
Adding items#
tasks = ["study"]
tasks.append("code") # one item at the end
tasks.insert(0, "wake up") # at a position
tasks.extend(["rest", "read"]) # several at once
print(tasks) # ['wake up', 'study', 'code', 'rest', 'read']append adds one thing; extend merges another list in. Using append with a list gives you a list inside a list, which is occasionally what you want and usually not.
Removing items#
tasks.remove("code") # by value — errors if it is not there
last = tasks.pop() # removes and returns the last item
first = tasks.pop(0) # removes and returns by position
del tasks[0] # removes by position
tasks.clear() # empties the listSorting#
numbers = [5, 2, 9, 1]
numbers.sort() # changes the list in place
print(numbers) # [1, 2, 5, 9]
ordered = sorted(numbers, reverse=True) # returns a new list
print(ordered) # [9, 5, 2, 1]
words = ["Banana", "apple", "Cherry"]
print(sorted(words, key=str.lower)) # case-insensitivesort() returns None. Writing numbers = numbers.sort() throws your list away — a genuinely common mistake.
Searching and counting#
names = ["Ada", "Sam", "Ada"]
print("Sam" in names) # True
print(names.count("Ada")) # 2
print(names.index("Sam")) # 1Useful whole-list functions#
scores = [72, 95, 61, 88]
print(len(scores)) # 4
print(sum(scores)) # 316
print(max(scores)) # 95
print(min(scores)) # 61
print(sum(scores) / len(scores)) # 79.0 — averageBuilding a new list#
prices = [100, 250, 80]
with_tax = []
for price in prices:
with_tax.append(round(price * 1.17))
# same thing, shorter
with_tax = [round(p * 1.17) for p in prices]
cheap = [p for p in prices if p < 150]Lists inside lists#
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(grid[1][2]) # 6
for row in grid:
for cell in row:
print(cell, end=" ")Questions people ask#
When should I use a tuple instead?
When the group should not change — coordinates, a fixed pair of values, a database row. Tuples also work as dictionary keys, which lists cannot.
How do I remove duplicates?
list(set(items)) is the quick way, but it loses the original order. To keep order: list(dict.fromkeys(items)).
Why does my sort put uppercase first?
Sorting compares character codes, and uppercase letters come before lowercase. Use key=str.lower for a human-friendly order.
Are lists slow?
Not for anything a beginner does. Appending and reading by position are fast. Repeatedly searching a large list with in is slower — a set or dictionary is better for that.