Python Lists in Depth
Move beyond simple variables. Master Lists to store, modify, sort, and comprehend large collections of data.
The Swiss Army Knife of Data
A List is Python's most flexible built-in data structure. It allows you to store multiple items in a specific order inside a single variable. Lists are mutable, meaning you can change them after they are created.
inventory = ["Sword", "Shield", "Health Potion"]
# Modifying an item by index
inventory[1] = "Magic Shield"Essential List Methods
append(item): Slaps a new item onto the very end of the list.insert(index, item): Squeezes a new item into a specific position.pop(): Removes and returns the last item (great for building stacks/queues).remove(item): Finds the first matching item and deletes it.sort(): Sorts the list alphabetically or numerically in place.
List Comprehensions: Python Magic
List comprehensions let you create a new list based on an existing one in just a single line of highly readable code. It combines a for loop and an if statement elegantly.
prices = [10, 20, 30, 40, 50]
# Traditional way:
# discounted = []
# for p in prices:
# if p > 25:
# discounted.append(p * 0.9)
# Pythonic way (Comprehension):
discounted = [p * 0.9 for p in prices if p > 25]