What is a List?
A list in Python is a collection of items that are ordered, changeable, and allow duplicate values. Think of it as a shopping list —you can add, remove, and change items anytime!
Why Use Lists?
- Stores multiple items in one variable
- Can hold different data types
- Super flexible!
Creating a List
Lists are created using square brackets []
.
fruits = ["apple", "banana", "cherry"]
print(fruits) # Outputs: ['apple', 'banana', 'cherry']
Lists can contain different data types:
random_list = [42, "hello", 3.14, True]
print(random_list)
Accessing List Items
You can access items by index (starting from 0
).
print(fruits[0]) # Outputs: apple
print(fruits[-1]) # Outputs: cherry (last item)
Modifying a List
Lists are mutable, meaning you can change them!
fruits[1] = "mango"
print(fruits) # Outputs: ['apple', 'mango', 'cherry']
Adding and Removing Items
Add items:
fruits.append("orange") # Adds to the end
fruits.insert(1, "grape") # Adds at index 1
print(fruits)
Remove items:
fruits.remove("mango") # Removes a specific item
popped_fruit = fruits.pop() # Removes and returns last item
print(fruits)
Looping Through a List
You can use a for
loop to iterate through a list.
for fruit in fruits:
print(fruit)
Summary
Concept | Description |
---|---|
List | A collection of ordered, changeable items |
Indexing | Access items using index numbers |
Mutability | Lists can be modified |
Methods | .append() , .insert() , .remove() , .pop() |
0 Comments