► Understanding Arrays and Lists
Lists (also called arrays in other languages) are ordered collections that can store multiple items in a single variable. Lists are mutable, meaning you can modify their contents after creation. They’re one of the most versatile and commonly used data structures in programming.
► Real-World Analogy
Think of a list like a shopping cart:
» You can add items to your cart (append)
» You can remove items you don’t want (remove)
» Items are in a specific order (indexed)
» You can check what’s at position 3 (access by index)
» You can count how many items are in the cart (length)
» You can rearrange items or empty the cart completely
► Key Concepts
✓ Ordered collection: Items maintain their position
✓ Mutable: Can be changed after creation
✓ Indexed: Access items using position (starting from 0)
✓ Dynamic size: Can grow or shrink as needed
✓ Mixed types: Can store different data types
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# Creating lists fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] mixed = ["hello", 42, True, 3.14] print(fruits) print(f"First fruit: {fruits[0]}") print(f"Last fruit: {fruits[-1]}") # Adding items fruits.append("mango") fruits.insert(1, "grape") print(f"After adding: {fruits}") # Removing items fruits.remove("banana") popped = fruits.pop() print(f"After removing: {fruits}") print(f"Popped item: {popped}") # List operations print(f"Length: {len(fruits)}") print(f"Is 'apple' in list? {'apple' in fruits}") # Slicing print(f"First two: {numbers[:2]}") print(f"Last two: {numbers[-2:]}") |
