Last updated

Python Lists

Definition: A list is an ordered collection of values stored in one variable, written in square brackets [ ]. Lists can be changed after creation.

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

Example 1 — accessing items (index starts at 0)

print(fruits[0])   # apple
print(fruits[1])   # banana
print(fruits[-1])  # cherry (last)

Example 2 — changing an item

fruits[1] = "blueberry"
print(fruits)

Example 3 — adding and removing

fruits.append("orange")    # add to end
fruits.insert(0, "mango")  # add at position 0
fruits.remove("apple")     # remove by value
print(fruits)

Example 4 — useful list tools

nums = [3, 1, 4, 1, 5]
print(len(nums))   # 5 items
print(max(nums))   # 5
print(min(nums))   # 1
print(sum(nums))   # 14
nums.sort()
print(nums)        # [1, 1, 3, 4, 5]

Example 5 — looping over a list

for fruit in ["a", "b", "c"]:
    print(fruit)

💡 Tip: lists can hold mixed types, but keeping one kind of thing per list (all numbers, or all names) keeps your code clear.

Try it Yourself
Output

          
Ad · responsive