Iterating Lists
Lists are ordered, mutable collections that can store any type of data. In Python, we can find the length of a list using len(list_name).
List Basics
If we are coming from C, think of lists as super-charged arrays. They handle resizing automatically and can store mixed data types.
# Type hinting: specify the element type(s) inside list[]
# See: [Modern Python Types](../1 - basics/1.9 - modern-python-types.md) for details
tech_stack: list[str | float] = ["Python", 3.12, "Bash"]
# Adding items to the end
tech_stack.append("C")
# Removing and returning the last item
last_added = tech_stack.pop()
print(tech_stack)
print(f"Removed: {last_added}")
Output:
['Python', 3.12, 'Bash']
Removed: C
Iteration
We can loop through a list directly. This is the Pythonic way compared to using index-based counters or manual incrementing.
ingredients = ["ginger", "cardamom", "cloves"]
for spice in ingredients:
print(f"Adding {spice}...")
Output:
Adding ginger...
Adding cardamom...
Adding cloves...
Worth Mentioning: Useful Methods
insert(index, item): Adds an item at a specific position.remove(item): Removes the first occurrence of a value.extend(collection): Appends all items from another collection.sort(): Sorts the list in place.