AnyCompiler

Lists

A list is an ordered, changeable collection — probably the single most-used data structure in Python. You can mix types in one list, though in practice most lists hold one type of thing.

fruits = ["apple", "banana", "cherry"]
print(fruits)
print(fruits[0])
print(fruits[-1])

fruits.append("date")
print(fruits)

fruits.remove("banana")
print(fruits)

print(len(fruits))
Output
['apple', 'banana', 'cherry']
apple
cherry
['apple', 'banana', 'cherry', 'date']
['apple', 'cherry', 'date']
3
  • fruits[0] gets the first item, fruits[-1] gets the last — negative indexes count from the end
  • .append() adds an item to the end of the list, in place
  • .remove() deletes the first matching item it finds
  • Lists are changeable (mutable) — unlike the tuples you'll see in the next lesson

Sorting

numbers = [5, 3, 1, 4, 2]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

.sort() sorts the list in place (it changes the original list and returns nothing) — reverse=True flips the order. If you need a sorted copy without touching the original, use sorted(numbers) instead.

Next: tuples — a list's immutable sibling, and when you'd actually reach for one.

Practice exercise

Create colors = ["red", "green", "blue"]. Append "yellow" to it, then print the list.